package com.qianniu.napi.admin.web.goods.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.mapper.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.GoodsActor;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.admin.service.akka.StoreActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.HttpUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品信息
 * </p>
 *
 * @author chenxuebin
 * @since 2018-06-23
 */
@RestController
public class GoodsController {

    private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ILogisticsService logisticsService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IGoodsMediaService goodsMediaService;
    @Autowired
    private IGoodsfavService goodsfavService;
    @Autowired
    private IGoodsExtService goodsExtService;
    @Autowired
    private IGoodsSkuService goodsSkuService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private RedissonClient redis;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IShareService shareService;
    @Autowired
    private IPintuanOpenService pintuanOpenService;
    @Autowired
    private IPintuanLogService pintuanLogService;
    @Autowired
    private IJizanLogService jizanLogService;
    @Autowired
    private ICutpriceOpenService cutpriceOpenService;
    @Autowired
    private ICutpriceHelpService cutpriceHelpService;
    @Autowired
    private IGoodsCategoryService goodscategoryService;
    @Autowired
    private IChoujiangService choujiangService;
    @Autowired
    private IChoujiangLogService choujiangLogService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IMusicService musicService;
    @Autowired
    private IGoodsMusicService goodsMusicService;
    @Autowired
    private IHdtemplateService hdtemplateService;
    @Autowired
    private StoreStatMapper storeStatMapper;
    @Autowired
    private ToupiaoLogMapper toupiaoLogMapper;
    @Autowired
    private GoodsToupiaoMapper goodsToupiaoMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private MdpayMapper mdpayMapper;
    @Autowired
    private LeagueMapper leagueMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private GoodsStoreMapper goodsStoreMapper;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @RequestMapping("/api/goods/baseInfo")
    @ResponseBody
    public Jinfo baseInfo(@RequestParam(value = "gid", required = false) Long gid,
                          HttpServletRequest req) {
        Jinfo json = new Jinfo();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("gid", gid);
        Goods goods = goodsService.selectById(gid);
        if (goods == null) {
            json.setCode(404);
            return json;
        }

        List<GoodsMedia> piclist = goodsMediaService.selectByMap(map);
        List<Logistics> logisticslist = logisticsService.selectByMap(map);
        GoodsCategory category = goodscategoryService.selectById(goods.getCid());

        map.clear();
        map.put("basicInfo", goods);
        map.put("pics", piclist);
        map.put("category", category);
        map.put("info", goods.getInfo());
        map.put("logistics", logisticslist);

        json.setInfo(map);

        return json;
    }

    @RequestMapping("/test/goodssku/detail")
    @ResponseBody
    public Jinfo goodsSkuDetail(@RequestParam(value = "gid", required = false) Long gid,
                                @RequestParam(value = "id", required = false) Long id,
                                HttpServletRequest req) {

        Jinfo info = new Jinfo();
        GoodsSku goodsSku = goodsSkuService.selectById(id);
        info.setInfo(goodsSku);
        return info;
    }

    @RequestMapping("/api/goods/detail")
    @ResponseBody
    public Jinfo goodsDetail(@RequestParam(value = "gid", required = false) String gid,
                             @RequestParam(value = "sid", required = false) Long sid,
                             @RequestParam(value = "jiaoyi", required = false) Integer jiaoyi,
                             @RequestParam(value = "isjifen", required = false) Integer isjifen,
                             @RequestParam(value = "s", required = false) String scene) {
        Jinfo json = new Jinfo();
        logger.info("========gid=" + gid);
        logger.info("========scene=" + scene);
        if (!Strings.isNullOrEmpty(gid) && "undefined".equals(gid) && !Strings.isNullOrEmpty(scene)) {
            String[] scenes = scene.split("_");
            if (scenes.length == 4) gid = scenes[3];
            logger.info("========process gid=" + gid);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("gid", gid);
        Goods goods = goodsService.selectById(gid);
        if (goods == null) {
            json.setCode(404);
            return json;
        }

        //浏览次数更新
        AkkaServer.system.actorOf(Props.create(GoodsActor.class))
                .tell(Constants.AKKA_MSG_GOODS_VIEW + "@" + goods.getId(), ActorRef.noSender());
        //商家信息
        Store store = storeService.selectById(goods.getSid());

        //商家浏览次数更新
        if (store != null) {
            AkkaServer.system.actorOf(Props.create(StoreActor.class))
                    .tell(Constants.AKKA_MSG_STORE_VIEW + "@" + store.getId(), ActorRef.noSender());
        }
        goods.setStore(store);
        Long uid = ObjectUtil.getUid();
        //活动收藏
        int cout = uid == null ? 0 : goodsfavService.selectCount(new EntityWrapper<Goodsfav>().eq("gid", goods.getId())
                .eq("uid", uid).eq("state", 1).eq("type", 1));
        goods.setShoucang(cout == 1);

        //店铺收藏
        cout = uid == null || store == null ? 0 : goodsfavService.selectCount(new EntityWrapper<Goodsfav>().eq("gid", store.getId())
                .eq("uid", uid).eq("state", 1).eq("type", 2));
        goods.setDpshoucang(cout == 1);

        MerchantConfig mc = redisService.getMconfig();
        Long mpid = ObjectUtil.getMpid();
        List<GoodsMedia> piclist = goodsMediaService.selectByMap(map);
        List<Logistics> logisticslist = logisticsService.selectByMap(map);
        GoodsCategory category = goodscategoryService.selectById(goods.getCid());
        Wrapper<GoodsSku> entity = new EntityWrapper<GoodsSku>()
                .setSqlSelect("id,gid,cid,characteristic,pic,price,xiangou,saleprice,saleprice,logistics_id logisticsId," +
                        "is_member isMember,is_jifen isJifen,is_coupon isCoupon,max_use_jifen maxUseJifen,gtype,extids,ext1,ext2,ext3,ext4,ext5,stores")
                .eq("mpid", mpid)
                .eq("gid", gid);

        List<GoodsSku> skulist = goodsSkuService.selectList(entity);

        if (goods.getHasSku() == 1 && skulist != null && skulist.size() > 0) {
            //add redis cache
            String rkey = "goods_detail_skugg_" + gid;
            String rkeymulExtids = "goods_detail_mulExtids_" + gid;
            String rkeySkuinfo = "goods_detail_skuinfo_" + gid;

            RBucket<String> bucket = redis.getBucket(rkey);
            RBucket<String> bucketmulExtids = redis.getBucket(rkeymulExtids);
            RBucket<String> bucketSkuinfo = redis.getBucket(rkeySkuinfo);
            if (bucket.isExists() && !Strings.isNullOrEmpty(bucket.get())) {
                map.put("skugg", bucket.get());
                map.put("mulExtids", bucketmulExtids.get());
                map.put("skuinfo", bucketSkuinfo.get());

            } else {
                List<String> skuids = new ArrayList<String>();
                TreeSet<String> exts = new TreeSet<String>();
                for (GoodsSku item : skulist) {
                    if (Strings.isNullOrEmpty(item.getExtids())) continue;

                    skuids.add(item.getId().toString());
                    String[] extsArr = item.getExtids().split("_");
                    for (String e : extsArr) {
                        exts.add(e);
                    }
                }

                logger.info("============exts=" + exts.toString());
                Wrapper<Config> centity = new EntityWrapper<Config>()
                        .setSqlSelect("pid").in("id", exts);//父类规格
//                   .setSqlSelect("id,name").in("id",skuids);//父类规格
//                   .setSqlSelect("id,name").in("id",ppsa).or().in("pid",ppsa);//父类规格
                logger.info("============centity=" + JSON.toJSONString(centity));
                List<Config> cslist = configService.selectList(centity);

                logger.info("============cslist=" + JSON.toJSONString(cslist));
                exts.clear();
                for (Config item : cslist) {
                    exts.add(item.getPid().toString());
                }
                centity = new EntityWrapper<Config>()
                        .setSqlSelect("id,name").in("id", exts).orderBy("sort");
                cslist = configService.selectList(centity);

                for (Config item : cslist) {
                    item.setChilds(new TreeSet<Config>());
                }
                logger.info("======after======cslist=" + JSON.toJSONString(cslist));

                //add sku info
//           Wrapper<GoodsSku> entity = new EntityWrapper<GoodsSku>()
//                   .setSqlSelect("id,gid,cid,characteristic,pic,price,xiangou,saleprice,saleprice,logistics_id logisticsId," +
//                           "is_member isMember,is_jifen isJifen,is_coupon isCoupon,max_use_jifen maxUseJifen,gtype,extids,ext1,ext2,ext3,ext4,ext5,stores").eq("gid",gid);
//           List<GoodsSku> goodsku = goodsSkuService.selectList(entity);

                List<GoodsSku> goodsku = skulist;
                TreeMap<String, GoodsSku> skuMap = new TreeMap<String, GoodsSku>();
                List<String> extidsList = new ArrayList<String>();
                TreeMap<String, Boolean> mulExtidsList = new TreeMap<String, Boolean>();
                for (GoodsSku item : goodsku) {
                    skuMap.put(item.getExtids(), item);
                    extidsList.add(item.getExtids());
                }
                for (String item : extidsList) {
                    String[] arr = item.split("_");
                    for (int i = 0; i < arr.length; i++) {
                        mulExtidsList.put(appendArr(arr, i), true);
                    }
                }
                map.put("mulExtids", JSON.toJSONString(mulExtidsList));
                map.put("skuinfo", JSON.toJSONString(skuMap));
                map.put("skuinfoIds", JSON.toJSONString(extidsList));

                if (mc.isCached()) bucketmulExtids.set(map.get("mulExtids").toString());
                if (mc.isCached()) bucketSkuinfo.set(map.get("skuinfo").toString());

                JSONArray jscon = new JSONArray();
                int m = 0;
                for (int i = 0; i < cslist.size(); i++) {
                    Config inc = cslist.get(i);
                    inc.setDisabled(false);
                    for (GoodsSku item : goodsku) {
                        String[] extids = item.getExtids().split("_");
                        String extidStart = null;
                        Config config = new Config();
                        config.setDisabled(false);
                        logger.info("======cslist.get()======" + i);
                        if (Strings.isNullOrEmpty(extids[i]) || extids[i].equals("null")) continue;
                        config.setId(Long.valueOf(extids[i]));
                        if (i == 0) {
                            //1级规格
                            config.setName(item.getExt1());
//                       extidStart = config.getId().toString();
                        }
                        if (i == 1) {
                            //2级规格
                            config.setName(item.getExt2());
//                       extidStart = selext.get(0)+"_"+config.getId().toString();
                        }
                        if (i == 2) {
                            //3级规格
                            config.setName(item.getExt3());
//                       extidStart = selext.get(0)+"_"+selext.get(1)+"_"+config.getId().toString();
                        }
                        if (i == 3) {
                            //4级规格
                            config.setName(item.getExt4());
//                       extidStart = selext.get(0)+"_"+selext.get(1)+"_"+selext.get(2)+"_"+config.getId().toString();
                        }
                        if (i == 4) {
                            config.setName(item.getExt5());
//                       extidStart = selext.get(0)+"_"+selext.get(1)+"_"+selext.get(2)+"_"+selext.get(3)+"_"+config.getId().toString();
                        }
//                   isMatch = matchStart(extidsList,extidStart);
//                   if(isFirst&&isMatch){
//                       config.setActive(isFirst);
//                       selext.add(config.getId().toString());//某级别的第一个可用可选规格
//                       isFirst = false;
//                   }
                        config.setSort(m + 1);
                        m++;
                        inc.getChilds().add(config);
                        m = inc.getChilds().size();
                        logger.info("======cslist.get()===for=over==" + i);
                    }
//               jscon.put(ppsa[i],inc);
                    jscon.add(inc);
                    inc.setSort(i + 1);
                    m = 0;
                }
                map.put("skugg", JSON.toJSONString(jscon, SerializerFeature.SortField));
                if (mc.isCached()) bucket.set(map.get("skugg").toString());
            }
        }

        Wrapper<Goodsfav> gentiy = new EntityWrapper<Goodsfav>().eq("uid", ObjectUtil.getUid())
                .eq("gid", gid).eq("state", 1);
        List<Goodsfav> goodsfav = goodsfavService.selectList(gentiy);

        map.put("basicInfo", goods);
        map.put("pics", piclist);
        map.put("category", category);
        map.put("info", goods.getInfo());
        map.put("logistics", logisticslist);

        if (ObjectUtil.getUid() != null && isjifen != null && isjifen == 1) {
            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", ObjectUtil.getUid()));
            map.put("jfamount", jifen == null ? 0 : jifen.getTotal());
        }

        // 神秘礼品
        if (goods.getType() == 2 && !Strings.isNullOrEmpty(goods.getXmtype())) {
            Goods liping = goodsService.selectOne(new EntityWrapper<Goods>().setSqlSelect("id,name")
                    .eq("id", goods.getXmtype()));
            if (liping != null) {
                Map<String, Object> smliping = new HashMap<String, Object>();
                smliping.put("gid", liping.getId());
                smliping.put("gname", liping.getName());
                map.put("smliping", smliping);
            }
        }
        //======添加评论======
        Page page = new Page(1, 2);
        Page<Comment> p = commentService.selectPage(page, new EntityWrapper<Comment>()
                .eq("gid", gid)
                .eq("state", 1).orderBy("id", false));
        List<Comment> pllist = p.getRecords();
        for (Comment item : pllist) {
            if (!Strings.isNullOrEmpty(item.getPic())) {
                item.setPicList(Arrays.asList(item.getPic().split(";")));
            }
        }
        map.put("pllist", pllist);
        //======添加评论 ======

        //======添加评论========
        if (jiaoyi != null && jiaoyi == 1) {
            Page page2 = new Page(1, 10);
            Page<Order> jyorders = orderService.selectPage(page2, new EntityWrapper<Order>()
                    .setSqlSelect("linkman,phone,createtime,goods_number goodsNumber")
                    .gt("status", 1).eq("state", 1)
                    .eq("mpid", ObjectUtil.getMpid())
                    .orderBy("id", false));

            List<Order> jylist = jyorders.getRecords();
            for (Order item : jylist) {
                item.setPhone(goodsService.replaceXing(item.getPhone()));
                item.setLinkman(goodsService.replaceMiddle(item.getLinkman()));
                item.setRemark(DateUtil.toDateString(item.getCreatetime(), "MM-dd hh:mm:ss"));
            }
            map.put("jylist", jylist);
        }
        //======交易记录 end======

        if (goodsfav == null || goodsfav.size() == 0) {
            map.put("isCollection", false);
        } else {
            map.put("isCollection", true);
        }

        json.setInfo(map);
        if (sid != null && sid.longValue() > 0) {
            json.setExtra(storeService.selectOne(new EntityWrapper<Store>()
                    .setSqlSelect("id,name,jianchen,pic,thumb,phone,wxno,qisongfee,peisongfee")
                    .eq("id", sid)));
        }
        return json;
    }

    //*** 针对华口云定制 ****
    @RequestMapping("/api/goods/hydetail")
    @ResponseBody
    public Jinfo hydetail(@RequestParam(value = "gid", required = false) Long gid,
                          @RequestParam(value = "cid", required = false) Long cid,
                          HttpServletRequest req) {

        Jinfo info = new Jinfo();
        int cout = goodsSkuService.selectCount(new EntityWrapper<GoodsSku>()
                .eq("cid", cid));
        if (cout > 0) {
            GoodsSku goodsSku = goodsSkuService.selectById(gid);
            if (goodsSku != null) {
                info.setInfo(goodsSku);
                return info;
            }
        }

        Goods goods = goodsService.selectById(gid);
        info.setInfo(goods);
        return info;
    }

    @RequestMapping("/api/goods/mdetail")
    @ResponseBody
    public Jinfo mdetailBycid(@RequestParam(value = "cid", required = false) Long cid,
                              @RequestParam(value = "sid", required = false) Long sid,
                              HttpServletRequest req) {
        Jinfo info = new Jinfo();
        Long mid = ObjectUtil.getMid();
        Goods goods = goodsService.selectOne(new EntityWrapper<Goods>()
                .setSqlSelect("id,name,pic,photos,jieshao,price,saleprice,has_sku hasSku,info,gtype,type,views,number_sale numberSale")
                .eq("mid", mid)
                .eq("cid", cid).eq("sid", sid));

        if (goods == null) {
            return info;
        }
        if (goods.getHasSku() != null && goods.getHasSku() == 1) {
            List<GoodsSku> skuList = goodsSkuService.selectList(new EntityWrapper<GoodsSku>()
                    .setSqlSelect("id,name,pic,jieshao,price,saleprice,info,gtype,type,views,number_sale numberSale").eq("gid", goods.getId()));
            goods.setSkuList(skuList);

        }
        info.setInfo(goods);
        return info;
    }

    @RequestMapping("/api/goods/hddetail")
    @ResponseBody
    public Jinfo hddetail(Long gid) {
        Jinfo info = new Jinfo();
        Goods goods = goodsService.selectById(gid);

        if (goods == null) {
            info.setCode(4);
            return info;
        }
        //优惠券大礼包
        if (goods.getType() == 7 && !Strings.isNullOrEmpty(goods.getQuans())) {
            String[] quans = goods.getQuans().split(";");
            List<String> quanslist = Arrays.asList(quans);
            List<CouponTpl> CouponTpls = couponTplService.selectBatchIds(quanslist);
            for (CouponTpl item : CouponTpls) {
                Store store = storeService.selectOne(new EntityWrapper<Store>()
                        .setSqlSelect("id,name,logo").eq("id", item.getSid()));
                item.setSname(store.getName());
                item.setSlogo(Strings.isNullOrEmpty(store.getLogo()) ? store.getPic() : store.getLogo());
            }

            info.setExtra(CouponTpls);
        }

        info.setInfo(goods);
        return info;
    }

    @RequestMapping("/api/goods/ext")
    @ResponseBody
    public Jinfo recommendedList(@RequestParam(value = "gid", required = false) long gid,
                                 HttpServletRequest req) {
        Jinfo json = new Jinfo();
        GoodsExt goodsExt = goodsExtService.selectOne(new EntityWrapper<GoodsExt>().eq("gid", gid));
        json.setInfo(goodsExt);
        return json;
    }

    //上下架
    @RequestMapping("/api/goods/shangxiajia")
    @ResponseBody
    public Jinfo shangxiajia(Goods goods) {
        Jinfo json = new Jinfo();
        if (goods.getId() == null || goods.getState() == null) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }
        goods.updateById();
        return json;
    }

    //活动审核
    @RequestMapping("/api/goods/shenhe")
    @ResponseBody
    public Jinfo shenhe(@RequestParam(value = "gid", required = false) long gid,
                        @RequestParam(value = "status", required = false) int status,
                        HttpServletRequest req) {
        Jinfo json = new Jinfo();
        Goods goods = goodsService.selectOne(new EntityWrapper<Goods>()
                .setSqlSelect("id,state,status,date_start startDate,date_end endDate").eq("id", gid));
        if (goods != null) {
            goods.setStatus(status);
            if (status == -1) {
                goods.setState(-1);
            } else if (status == 2) {
                Date now = new Date();
                //goods.getStartDate() == null 商品审核
                //now.getTime() >= goods.getStartDate().getTime()... 活动审核
                if (goods.getStartDate() == null || (now.getTime() >= goods.getStartDate().getTime() &&
                        now.getTime() <= goods.getEndDate().getTime())) {
                    //===待实现，未付费商家只能上线一个活动
                    //默认审核通过后上线
                    goods.setState(1);
                } else {
                    goods.setState(-1);
                }
            }
            goods.setModifier(ObjectUtil.getUid());
            goods.setModifytime(new Date());
            goods.updateById();
        }
        return json;
    }

    @RequestMapping("/api/goods/recommended/list")
    @ResponseBody
    public Jinfo recommendedList(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                                 @RequestParam(value = "pageSize", required = false) int pageSize,
                                 HttpServletRequest req) {
        Jinfo json = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        Long mid = ObjectUtil.getMid();
        map.put("mid", mid);
        Page page = new Page(pageIndex, pageSize);

        Page<Goods> list = goodsService.selectPage(page, new EntityWrapper<Goods>()
                .eq("mid", mid)
                .eq("is_deleted", -1)
                .eq("is_recommended", 1)
                .eq("state", 1).orderBy("id"));

        json.setInfo(list.getRecords());
        return json;
    }

    @RequestMapping("/api/goods/shangjia")
    @ResponseBody
    public Jinfo shangjia(int state, long gid) {
        Jinfo json = new Jinfo();
        Goods goods = goodsService.selectOne(new EntityWrapper<Goods>()
                .setSqlSelect("id,state")
                .eq("id", gid));
        if (goods == null) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }
        if (state != 1 && state != -1) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }
        goods.setState(state);
        goods.updateById();

        return json;
    }

    //获取目录商品，通过cid查询，cid == -2:查询会员商品；cid==0时，查询全部商品
    @RequestMapping("/api/goods/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "cid", required = false) Long cid,
                      @RequestParam(value = "sid", required = false) Long sid,
                      @RequestParam(value = "orderby", required = false) Integer orderby,
                      @RequestParam(value = "isadmin", required = false) Integer isadmin,
                      @RequestParam(value = "sort", required = false) Integer sort,
                      @RequestParam(value = "pname", required = false) String pname,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo json = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();

        //默认分类的第一页商品（前10）目缓存到redis
        String rkey = Constants.REDIS_GOODS_LIST + mid + "_" + ObjectUtil.getMpid() + "_" + cid + "_" + pageIndex;
        MerchantConfig mc = redisService.getMconfig();
        logger.debug("========rkey=" + rkey);
        List<Goods> goods = redisService.get(rkey);
        //Strings.isNullOrEmpty(pname) 不是搜索
        boolean notsou = Strings.isNullOrEmpty(pname);
        if (notsou && goods != null && goods.size() > 0) {
            logger.debug("========rkey value=" + goods);
            json.setInfo(goods);
            return json;
        }

        Page page = new Page(pageIndex, pageSize);

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>();
        if (cid != null && cid == -2) wrapper.isNotNull("hyprice");
        else if (cid != null && cid != 0) wrapper.eq("cid", cid);
        else wrapper.gt("cid", 0);

        if (sid != null && sid > 0) wrapper.eq("sid", sid);
        else wrapper.eq("sid", 0);
        //只支持一个字段搜索
//       if (!Strings.isNullOrEmpty(pname)) wrapper.like("name", pname).or().like("characteristic", pname);

        if (!notsou) wrapper.like("name", pname);
        wrapper.eq("mpid", mpid);
        if (isadmin == null) wrapper.eq("state", 1);

        String by = "cid";
        if (orderby != null) {
            switch (orderby) {
                case 1:
                    by = "number_sale";
                    break;
                case 2:
                    by = "createtime";
                    break;
                case 3:
                    by = "saleprice";
                    break;
                default:
                    by = "sort";
                    sort = -1;
            }
            wrapper.orderBy(by, sort == -1);
        } else {
            wrapper.orderBy("sort");
        }

        //华口云特殊过滤
        User user = redisService.getUser();
        if (ObjectUtil.getMpid() == 11 && user != null && user.getIsPlatform() != 1 && user.getIsMch() != 1
                && cid != null && (cid == 0 || cid == 828)) {
            wrapper.ne("cid", 808);
        } else if (ObjectUtil.getMpid() == 11 && user == null && cid != null && (cid == 0 || cid == 828)) {
            wrapper.ne("cid", 808);
        }

        Page<Goods> list = goodsService.selectPage(page, wrapper);
        List<Goods> glist = list.getRecords();
        if (glist != null && glist.size() > 0 && cid != null && cid > 0) {
            for (Goods g : glist) {
                g.setNumber(0);
            }
        }
        json.setInfo(list.getRecords());
        if (pageIndex <= 1 && mc.isCached() && !notsou) redisService.set(rkey, list.getRecords());
//       else if (pageIndex == 2 && pageIndex < 10 && mc.isCached())
//           redisService.set(rkey, list.getRecords(), 10, TimeUnit.MINUTES);
        return json;
    }


    //商家独立版
    //获取目录商品，通过cid查询，cid == -2:查询会员商品；cid==0时，查询全部商品
    @RequestMapping("/api/goods/list10")
    @ResponseBody
    public Jinfo list10(@RequestParam(value = "cid", required = false) Long cid,
                        @RequestParam(value = "sid", required = false) Long sid,
                        @RequestParam(value = "orderby", required = false) Integer orderby,
                        @RequestParam(value = "isadmin", required = false) Integer isadmin,
                        @RequestParam(value = "sort", required = false) Integer sort,
                        @RequestParam(value = "pname", required = false) String pname,
                        @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                        HttpServletRequest req) {
        Jinfo json = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();

        //默认分类的第一页商品（前10）目缓存到redis
        String rkey = Constants.REDIS_GOODS_LIST + mid + "_" + ObjectUtil.getMpid() + "_" + cid + "_" + pageIndex;
        MerchantConfig mc = redisService.getMconfig();
        logger.debug("========rkey=" + rkey);
        List<Goods> goods = redisService.get(rkey);
        //Strings.isNullOrEmpty(pname) 不是搜索
        boolean notsou = Strings.isNullOrEmpty(pname);
        if (notsou && goods != null && goods.size() > 0) {
            logger.debug("========rkey value=" + goods);
            json.setInfo(goods);
            return json;
        }

        Page page = new Page(pageIndex, pageSize);

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>();
        if (cid != null && cid == -2) wrapper.isNotNull("hyprice");
        else if (cid != null && cid != 0) wrapper.eq("cid", cid);
        else wrapper.gt("cid", 0);

        if (sid != null && sid > 0) wrapper.eq("sid", sid);
        else {
            List<Store> storelist = storeService.selectList(new EntityWrapper<Store>().eq("state", 1).eq("mpid", mpid));
            if (storelist == null || storelist.size() <= 1) {
                //wrapper.eq("sid", store.getId());
            } else {

            }
        }
        //只支持一个字段搜索
//       if (!Strings.isNullOrEmpty(pname)) wrapper.like("name", pname).or().like("characteristic", pname);

        if (!notsou) wrapper.like("name", pname);
        wrapper.eq("mpid", mpid);
        if (isadmin == null) wrapper.eq("state", 1);

        String by = "cid";
        if (orderby != null) {
            switch (orderby) {
                case 1:
                    by = "number_sale";
                    break;
                case 2:
                    by = "createtime";
                    break;
                case 3:
                    by = "saleprice";
                    break;
                default:
                    by = "sort";
                    sort = -1;
            }
            wrapper.orderBy(by, sort == -1);
        } else {
            wrapper.orderBy("sort");
        }

        Page<Goods> list = goodsService.selectPage(page, wrapper);
        List<Goods> glist = list.getRecords();
        if (glist != null && glist.size() > 0 && cid != null && cid > 0) {
            for (Goods g : glist) {
                g.setNumber(0);
            }
        }
        json.setInfo(list.getRecords());
        if (pageIndex <= 1 && mc.isCached() && !notsou) redisService.set(rkey, list.getRecords());
//       else if (pageIndex == 2 && pageIndex < 10 && mc.isCached())
//           redisService.set(rkey, list.getRecords(), 10, TimeUnit.MINUTES);
        return json;
    }

    //平台版《商户商品管理》
    //获取目录商品，通过cid查询，cid == -2:查询会员商品；cid==0时，查询全部商品
    @RequestMapping("/api/goods/mchlist")
    @ResponseBody
    public Jinfo mchlist(@RequestParam(value = "cid", required = false) Long cid,
                         @RequestParam(value = "sid", required = false) Long sid,
                         @RequestParam(value = "orderby", required = false) Integer orderby,
                         @RequestParam(value = "sort", required = false) Integer sort,
                         @RequestParam(value = "pname", required = false) String pname,
                         @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                         @RequestParam(value = "pageSize", required = false) Integer pageSize,
                         HttpServletRequest req) {
        Jinfo json = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 20;
        Long mpid = ObjectUtil.getMpid();

        Page page = new Page(pageIndex, pageSize);

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>();
        if (cid != null && cid == -2) wrapper.isNotNull("hyprice");
        else if (cid != null && cid != 0) wrapper.eq("cid", cid);
        else wrapper.gt("cid", 0);

        if (sid == null) sid = ObjectUtil.getSid();
        wrapper.eq("sid", sid);

        //只支持一个字段搜索
        if (!Strings.isNullOrEmpty(pname)) wrapper.andNew().like("name", pname).or().like("characteristic", pname);

        wrapper.eq("mpid", mpid);
        wrapper.orderBy("id", false);

        Page<Goods> list = goodsService.selectPage(page, wrapper);
        List<Goods> glist = list.getRecords();
        if (glist != null && glist.size() > 0 && cid != null && cid > 0) {
            for (Goods g : glist) {
                g.setNumber(0);
            }
        }
        json.setInfo(list.getRecords());
        return json;
    }

    //商超商品查询接口
    //同时返回二级类目和所有商品
    //获取目录商品，通过cid查询，cid == -2:查询会员商品；cid==0时，查询全部商品
    @RequestMapping("/api/goods/shaolist")
    @ResponseBody
    public Jinfo shaolist(@RequestParam(value = "cid", required = false) Long cid,
                          @RequestParam(value = "sid", required = false) Long sid,
                          @RequestParam(value = "sku", required = false) Integer sku,
                          @RequestParam(value = "orderby", required = false) Integer orderby,
                          @RequestParam(value = "s", required = false) String s) {
        Jinfo json = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        MerchantConfig mc = redisService.getMconfig();
        List<Goods> goods = null;
        List<GoodsCategory> goodsCategories = new ArrayList<GoodsCategory>();
        List<GoodsCategory> categories = new ArrayList<GoodsCategory>();
        //不是搜索 Strings.isNullOrEmpty(pname)
        boolean notsou = Strings.isNullOrEmpty(s);
        String rgckey = Constants.REDIS_GOODS_CATEGORY_LIST + ObjectUtil.getMpid() + "_" + cid + "_" + sid;
        String rckey = Constants.REDIS_CATEGORY_LIST + ObjectUtil.getMpid() + "_" + cid + "_" + sid;
        String rgkey = Constants.REDIS_GOODS_LIST + ObjectUtil.getMpid() + "_" + cid + "_" + sid;

        //先查询缓存，非活动商品
        if (cid != null && cid.longValue() > 0) {
            //默认分类的第一页商品（前10）目缓存到redis，针对普通商品

            logger.debug("========rgckey=" + rgckey);
            categories = redisService.get(rckey);
            goodsCategories = redisService.get(rgckey);

            Wrapper<GoodsCategory> cwrapper = null;
            if (categories == null || categories.size() == 0) {
                //先查询分类
                cwrapper = new EntityWrapper<GoodsCategory>().setSqlSelect("id,name,pic,has_child hasChild")
                        .eq("state", 1).eq("pid", cid).orderBy("paixu");
                categories = goodscategoryService.selectList(cwrapper);

                if (categories == null || categories.size() == 0) {
                    cwrapper = new EntityWrapper<GoodsCategory>().setSqlSelect("id,name,pic,has_child hasChild")
                            .eq("state", 1).eq("id", cid);
                    categories = goodscategoryService.selectList(cwrapper);
                }
            }

            if (notsou && goodsCategories != null && goodsCategories.size() > 0) {
                logger.debug("========rgckey value=" + goodsCategories);
                json.setInfo(goodsCategories);
                json.setData(categories);
                return json;
            }
            cwrapper = new EntityWrapper<GoodsCategory>().setSqlSelect("id,name,pic")
                    .eq("state", 1).eq("pid", cid).orderBy("paixu");
            goodsCategories = goodscategoryService.selectList(cwrapper);

            if (goodsCategories == null || goodsCategories.size() == 0) {
                cwrapper = new EntityWrapper<GoodsCategory>().setSqlSelect("id,name,pic")
                        .eq("state", 1).eq("id", cid);
                goodsCategories = goodscategoryService.selectList(cwrapper);
            }
        }
        //先查询缓存，活动商品
        if (notsou && cid != null && cid.longValue() < 0) {
            //默认分类的第一页商品（前10）目缓存到redis，针对活动商品

            logger.debug("rgkey" + rgkey);
            goods = redisService.get(rgkey);

            if (notsou && goods != null && goods.size() > 0) {
                logger.debug("========rgkey value=" + goods);
                json.setInfo(goods);
                json.setExtra(true);
                return json;
            }
        }

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>().eq("state", 1)
                .setSqlSelect("id,name,thumb,pic,type,xiangou,stores,cid,gtype,number_sale numberSale,price,hyprice,saleprice,has_sku hasSku,mpid")
                .eq("mpid", mpid);
        if (sid != null && sid.longValue() > 0) wrapper.eq("sid", sid);//入驻门店

        //默认按照销量排序
        String by = "number_sale";
        if (orderby != null) {
            switch (orderby) {
                case 1:
                    by = "number_sale";
                    break;
                case 2:
                    by = "id";
                    break;
                case 3:
                    by = "saleprice";
                    break;
                default:
                    by = "number_sale";
            }
            wrapper.orderBy(by, false);
        }

        if (!notsou) {
            //处理搜索，不循环商品分类
            wrapper.like("name", s);
            goods = goodsService.selectList(wrapper);
            goods = sku == null || sku != 1 ? goods : processSKuGoods(goods);
            json.setInfo(goods);
            json.setExtra(true);//搜索返回项目，不显示二级分类
            //不设置缓存
        } else if (cid != null && cid == -2) {
            wrapper.isNotNull("hyprice");
            goods = goodsService.selectList(wrapper);
            goods = sku == null || sku != 1 ? goods : processSKuGoods(goods);
            json.setInfo(goods);
            json.setExtra(true);//搜索返回项目，不显示二级分类
            //设置缓存
            if (mc.getIsCache() == 1)
                redisService.set(rgkey, goods, 10, TimeUnit.MINUTES);

        } else if (cid != null && cid < 0) {

            json.setExtra(true);//搜索返回项目，不显示二级分类
            //设置缓存
        } else {
            for (GoodsCategory item : goodsCategories) {
                Wrapper<Goods> gwrapper = new EntityWrapper<Goods>().eq("state", 1)
                        .setSqlSelect("id,name,thumb,pic,type,xiangou,stores,cid,gtype,number_sale numberSale,price,hyprice,saleprice,has_sku hasSku,mpid")
                        .eq("mpid", mpid).orderBy(by, false);

                if (sid != null && sid.longValue() > 0) gwrapper.eq("sid", sid);//入驻门店

                gwrapper.eq("cid", item.getId());
                goods = goodsService.selectList(gwrapper);
                item.setGoods(sku == null || sku != 1 ? goods : processSKuGoods(goods));
            }
            json.setInfo(goodsCategories);
            json.setData(categories);
            //设置缓存
            if (mc.getIsCache() == 1) {
                redisService.set(rckey, categories, 10, TimeUnit.MINUTES);
                redisService.set(rgckey, goodsCategories, 10, TimeUnit.MINUTES);
            }
        }

        return json;
    }

    @RequestMapping("/api/goods/hylist")
    @ResponseBody
    public Jinfo hylist(@RequestParam(value = "cid", required = false) Long cid,
                        HttpServletRequest req) {
        Jinfo json = new Jinfo();
        List<GoodsSku> list = goodsSkuService.selectList(new EntityWrapper<GoodsSku>()
                .eq("cid", cid)
                .eq("state", 1)
                .eq("sid", 0)
        );
        if (list != null && list.size() > 0) {
            json.setInfo(list);
            return json;
        }
        List<Goods> list2 = goodsService.selectList(new EntityWrapper<Goods>()
                .eq("cid", cid)
                .eq("state", 1)
                .eq("sid", 0));
        json.setInfo(list2);

        return json;
    }

    @RequestMapping("/api/goods/hylist2")
    @ResponseBody
    public Jinfo hylist2(@RequestParam(value = "cid", required = false) Long cid,
                         @RequestParam(value = "lat", required = false) Double lat,
                         @RequestParam(value = "lng", required = false) Double lng,
                         @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                         @RequestParam(value = "pageSize", required = false) Integer pageSize,
                         HttpServletRequest req) {
        Jinfo json = new Jinfo();
        if (pageSize == null) pageSize = 10;
        if (pageIndex == null) pageIndex = 1;
        Map map = new HashMap<String, Object>();
        map.put("cid", cid);
        map.put("lat", lat);
        map.put("lng", lng);
        map.put("skip", (pageIndex - 1) * pageSize);
        map.put("size", pageSize);
        map.put("mpid", ObjectUtil.getMpid());

        List<Goods> list = goodsMapper.getGoodsHylistByMap(map);
        json.setInfo(list);

        return json;
    }

    @RequestMapping("/api/goodsstore/list")
    @ResponseBody
    public Jinfo goodsstore(@RequestParam(value = "orderby", required = false) Integer orderby,
                            @RequestParam(value = "sort", required = false) Integer sort,
                            @RequestParam(value = "pname", required = false) String pname,
                            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo json = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 20;
        Long mpid = ObjectUtil.getMpid();
        logger.info("==============================pname=" + pname);

        MerchantConfig mc = redisService.getMconfig();
//       logger.debug("========rkey=" + rkey);
//       List<Goods> goods = redisService.get(rkey);
//       //Strings.isNullOrEmpty(pname) 不是搜索
//       boolean notsou = Strings.isNullOrEmpty(pname);
//       if (notsou && goods != null && goods.size() > 0) {
//           logger.debug("========rkey value=" + goods);
//           json.setInfo(goods);
//           return json;
//       }

        Page page = new Page(pageIndex, pageSize);

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>();
//       if (cid != null && cid != 0) wrapper.eq("cid", cid);
//       else  wrapper.gt("cid", 0);
//       if (sid != null && sid > 0) wrapper.eq("sid", sid);
//       else wrapper.eq("sid", 0);
        //只支持一个字段搜索
//       if (!Strings.isNullOrEmpty(pname)) wrapper.like("name", pname).or().like("characteristic", pname);

        if (!Strings.isNullOrEmpty(pname)) wrapper.like("name", pname);
        wrapper.eq("mpid", mpid);
        wrapper.eq("state", 1);

        String by = "cid";
        if (orderby != null) {
            switch (orderby) {
                case 1:
                    by = "number_sale";
                    break;
                case 2:
                    by = "createtime";
                    break;
                case 3:
                    by = "saleprice";
                    break;
                default:
                    by = "createtime";
            }
            wrapper.orderBy(by, sort == -1);
        }

        Page<Goods> list = goodsService.selectPage(page, wrapper);
        json.setInfo(list.getRecords());

        //stores
        Wrapper<Store> swrapper = new EntityWrapper<Store>();
        page = new Page(pageIndex, pageSize);
        if (!Strings.isNullOrEmpty(pname)) swrapper.like("name", pname);
        swrapper.eq("mpid", mpid);
        swrapper.eq("state", 1);
        Page<Store> slist = storeService.selectPage(page, swrapper);
        json.setExtra(slist.getRecords());

        return json;
    }

    /*
     商家展示商品
     */
    @RequestMapping("/api/goods/mlist")
    @ResponseBody
    public Jinfo mlist(@RequestParam(value = "orderby", required = false) Integer orderby,
                       @RequestParam(value = "pname", required = false) String pname,
                       @RequestParam(value = "type", required = false) Integer type,
                       @RequestParam(value = "ptype", required = false) Integer ptype,
                       @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                       @RequestParam(value = "pageSize", required = false) Integer pageSize,
                       HttpServletRequest req) {
        Jinfo json = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;
        Long mpid = ObjectUtil.getMpid();
        Long sid = ObjectUtil.getSid();
        logger.info("---------------------------goods/mlist sid=" + sid);
        logger.info("---------------------------goods/mlist type=" + type);
        logger.info("---------------------------goods/mlist ptype=" + ptype);

        Page page = new Page(pageIndex, pageSize);

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>();
        if (sid != null && sid > 0) {
            wrapper.eq("type", -1);
            wrapper.eq("sid", sid);
        } else {
            wrapper.eq("sid", 0);
            String[] types = new String[]{"0", "4"};
            wrapper.in("type", types);
        }

        if (!Strings.isNullOrEmpty(pname)) wrapper.and().like("name", pname).or().like("characteristic", pname);
        wrapper.eq("mpid", mpid);

        String by = "createtime";
        if (orderby != null) {
            switch (orderby) {
                case 1:
                    by = "number_sale";
                    break;
                case 2:
                    by = "createtime";
                    break;
                case 3:
                    by = "saleprice";
                    break;
                default:
                    by = "createtime";
            }
            wrapper.orderBy(by, false);
        } else {
            wrapper.orderBy("id", false);
        }

        Page<Goods> list = goodsService.selectPage(page, wrapper);
        json.setInfo(list.getRecords());

        return json;
    }

    /*
     行业订单，针对C端
     */
    @RequestMapping("/api/goods/yxlist")
    @ResponseBody
    public Jinfo yxlist(@RequestParam(value = "orderby", required = false) String orderby,
                        @RequestParam(value = "search", required = false) String search,
                        @RequestParam(value = "shicode", required = false) String shicode,
                        @RequestParam(value = "status", required = false) String status,
                        @RequestParam(value = "lat", required = false) Double lat,
                        @RequestParam(value = "lng", required = false) Double lng,
                        @RequestParam(value = "hytype", required = false) String hytype,
                        @RequestParam(value = "yxtype", required = false) String yxtype,
                        @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                        HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;

        Long mpid = ObjectUtil.getMpid();
        logger.info("==============================yxtype=" + yxtype);
        logger.info("==============================hytype=" + hytype);
        List<Goods> list = goodsService.getYxgoodsList(pageIndex, pageSize, lat, lng, mpid, hytype, yxtype, shicode, status, orderby);

        if (list != null) {
            for (Goods item : list) {
                item.setYxtypeName(Constants.YX_TYPE_MAP.get(item.getType().toString()));
                item.setHytypeName(Constants.HY_TYPE_MAP.get(item.getHytype().toString()));
            }
        }
        info.setInfo(list);
        return info;
    }

    /*
     行业订单，有联盟商家
     */
    @RequestMapping("/api/goods/lmyxlist")
    @ResponseBody
    public Jinfo lmyxlist(@RequestParam(value = "orderby", required = false) String orderby,
                          @RequestParam(value = "search", required = false) String search,
                          @RequestParam(value = "shicode", required = false) String shicode,
                          @RequestParam(value = "lat", required = false) Double lat,
                          @RequestParam(value = "lng", required = false) Double lng,
                          @RequestParam(value = "hytype", required = false) String hytype,
                          @RequestParam(value = "yxtype", required = false) String yxtype,
                          @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                          @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;

        Long mpid = ObjectUtil.getMpid();
        logger.info("==============================yxtype=" + yxtype);
        logger.info("==============================hytype=" + hytype);
        List<Goods> list = goodsService.getYxgoodslmList(pageIndex, pageSize, lat, lng, mpid, hytype, yxtype, shicode, orderby);

        info.setInfo(list);

        if (pageIndex.intValue() == 1) {
            Map map = new HashMap<String, Object>();
            map.put("mpid", mpid);
            map.put("lat", lat);
            map.put("lng", lng);
            League league = leagueMapper.getNearbyLm(map);
            if (league != null) {
                info.setExtra(league);
                info.setData(1);//联盟
            } else {
                Store store = storeMapper.selectNearestStores(map);
                if (store != null) {
                    info.setExtra(store);
                    info.setData(2);//商家店铺
                }
            }
        }

        return info;
    }

    /*
     爆款营销商品=非实体商家爆款商品+实体商家爆款商品
     */
    @RequestMapping("/api/goods/bkyxlist")
    @ResponseBody
    public Jinfo bkyxlist(@RequestParam(value = "orderby", required = false) String orderby,
                          @RequestParam(value = "search", required = false) String search,
                          @RequestParam(value = "shicode", required = false) String shicode,
                          @RequestParam(value = "lat", required = false) Double lat,
                          @RequestParam(value = "lng", required = false) Double lng,
                          @RequestParam(value = "hytype", required = false) String hytype,
                          @RequestParam(value = "yxtype", required = false) String yxtype,
                          @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                          @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;

        Long mpid = ObjectUtil.getMpid();
        logger.info("==============================yxtype=" + yxtype);
        logger.info("==============================hytype=" + hytype);
        List<Goods> list = goodsService.getYxbkgoodsList(pageIndex, pageSize, lat, lng, mpid, hytype, yxtype, shicode, orderby);

        info.setInfo(list);

        if (pageIndex.intValue() == 1) {
            Map map = new HashMap<String, Object>();
            map.put("mpid", mpid);
            map.put("lat", lat);
            map.put("lng", lng);
            League league = leagueMapper.getNearbyLm(map);
            if (league != null) {
                info.setExtra(league);
                info.setData(1);//联盟
            } else {
                Store store = storeMapper.selectNearestStores(map);
                if (store != null) {
                    info.setExtra(store);
                    info.setData(2);//商家店铺
                }
            }
        }

        return info;
    }

    /*
     * 附近优惠活动，包含联盟活动
     */
    @RequestMapping("/api/goods/yxlist2")
    @ResponseBody
    public Jinfo yxlist2(@RequestParam(value = "orderby", required = false) String orderby,
                         @RequestParam(value = "search", required = false) String search,
                         @RequestParam(value = "shicode", required = false) String shicode,
                         @RequestParam(value = "lat", required = false) Double lat,
                         @RequestParam(value = "lng", required = false) Double lng,
                         @RequestParam(value = "hytype", required = false) String hytype,
                         @RequestParam(value = "yxtype", required = false) String yxtype,
                         @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                         @RequestParam(value = "pageSize", required = false) Integer pageSize,
                         HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;

        Long mpid = ObjectUtil.getMpid();
        logger.info("==============================yxtype=" + yxtype);
        logger.info("==============================hytype=" + hytype);
        List<Goods> list = goodsService.getYxgoodsList2(pageIndex, pageSize, lat, lng, mpid, hytype, yxtype, shicode, orderby);

        if (list != null) {
            for (Goods item : list) {
                item.setYxtypeName(Constants.YX_TYPE_MAP.get(item.getType().toString()));
                item.setHytypeName(Constants.HY_TYPE_MAP.get(item.getHytype().toString()));
            }
        }
        info.setInfo(list);
        return info;
    }

    /*
     活动管理列表，针对商家端+联盟端
     */
    @RequestMapping("/api/goods/hdlist")
    @ResponseBody
    public Jinfo hdlist(@RequestParam(value = "search", required = false) String search,
                        @RequestParam(value = "type", required = false) Integer type,
                        @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;

        Long mpid = ObjectUtil.getMpid();
        Page page = new Page(pageIndex, pageSize);
        Wrapper<Goods> wrapper = new EntityWrapper<Goods>().setSqlSelect("id,name,thumb,pic,type,status,state,ptotal,gtype,date_end dateEnd,number_orders numberOrders,number_sale numberSale,price,saleprice,stores,canyushu,fenxiaoshu,hexiaoshu,views,sharenum")
                .eq("mpid", mpid).eq("is_deleted", -1);

        User user = redisService.getUser();

        if (user == null) {
            info.setCode(1);
            info.setMsg("请授权登录后再操作");
            return info;
        } else if (user.getIsPlatform() == 1) {

        } else if (ObjectUtil.getSid() != null && ObjectUtil.getSid().longValue() > 0)
            wrapper.eq("sid", ObjectUtil.getSid());
        else if (redisService.getLeagueid() != null && redisService.getLeagueid().longValue() > 0)
            wrapper.eq("leagueid", redisService.getLeagueid());
        else {
            info.setCode(1);
            info.setMsg("请授权登录后再操作");
            return info;
        }
        if (type == null || type == 99) wrapper.ge("type", 1);
        else wrapper.eq("type", type);

        wrapper.orderBy("id", false);

        Page<Goods> list = goodsService.selectPage(page, wrapper);
        List<Goods> goods = list.getRecords();
        for (Goods item : goods) {
            if (item.getType().intValue() == YXType.toupiao.getVal()) {
                item.setToupiao(goodsToupiaoMapper.selectById(item.getId()));
            }
        }
        info.setInfo(goods);
        return info;
    }

    /*
     模板活动管理列表，针对商家+联盟+平台端
     */
    @RequestMapping("/api/goods/hdmblist")
    @ResponseBody
    public Jinfo hdmblist(@RequestParam(value = "search", required = false) String search,
                          @RequestParam(value = "type", required = false) Integer type,
                          @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                          @RequestParam(value = "pageSize", required = false) Integer pageSize,
                          HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;

        Long mpid = ObjectUtil.getMpid();
        Page page = new Page(pageIndex, pageSize);
        Wrapper<Goods> wrapper = new EntityWrapper<Goods>().eq("mpid", mpid).eq("is_deleted", -1);

        if (type == null || type == 99) wrapper.ge("type", 1);
        else wrapper.eq("type", type);

        wrapper.orderBy("id", false);

        Page<Goods> list = goodsService.selectPage(page, wrapper);
        List<Goods> goods = list.getRecords();
        for (Goods item : goods) {
            if (item.getType().intValue() == YXType.toupiao.getVal()) {
                item.setToupiao(goodsToupiaoMapper.selectById(item.getId()));
            }
        }
        info.setInfo(goods);
        return info;
    }

    /*
     活动审核列表，针对平台端
     */
    @RequestMapping("/api/goods/hdlistsh")
    @ResponseBody
    public Jinfo hdlistsh(@RequestParam(value = "search", required = false) String search,
                          @RequestParam(value = "type", required = false) Integer type,
                          @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                          @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;

        Long mpid = ObjectUtil.getMpid();
        Page page = new Page(pageIndex, pageSize);
        Wrapper<Goods> wrapper = new EntityWrapper<Goods>()
                .eq("mpid", mpid).eq("is_deleted", -1);

        if (type == null || type == 99) wrapper.ge("type", 0);
        else wrapper.eq("type", type);

        wrapper.orderBy("id", false).orderBy("modifytime", false);

        Page<Goods> list = goodsService.selectPage(page, wrapper);
        info.setInfo(list.getRecords());
        return info;
    }

    @RequestMapping("/api/goods/modify")
    @ResponseBody
    public Jinfo amodify(@Valid Goods bean, GoodsToupiao toupiao, BindingResult result, String dateStart, String dateEnd) {
        Jinfo info = new Jinfo();
        logger.debug("==========api/goods/modify=" + JSON.toJSONString(bean));

        if (bean.getPhotos() != null) {
            List<String> pics = Arrays.asList(bean.getPhotos().split(";"));
            bean.setPic(pics.get(0));
        } else {
            bean.setPhotos(bean.getPic());
            if (!Strings.isNullOrEmpty(bean.getPic())) {
                List<String> pics = Arrays.asList(bean.getPic().split(";"));
                bean.setPic(pics.get(0));
            }
        }

//        //date_start
//        if (!Strings.isNullOrEmpty(dateStart)&&dateStart.trim().length()==10) {
//            dateStart+=" 00:00:00";
//            bean.setDateStart(DateUtil.toDate(dateStart));
//        }else if (!Strings.isNullOrEmpty(dateStart)&&dateStart.trim().length()==16) {
//            dateStart+=":00";
//            bean.setDateStart(DateUtil.toDate(dateStart));
//        }
//        //date_end
//        if (!Strings.isNullOrEmpty(dateEnd)&&dateEnd.trim().length()==10) {
//            dateEnd+=" 00:00:00";
//            bean.setDateEnd(DateUtil.toDate(dateEnd));
//        }else if (!Strings.isNullOrEmpty(dateEnd)&&dateEnd.trim().length()==16) {
//            dateEnd+=":59";
//            bean.setDateEnd(DateUtil.toDate(dateEnd));
//        }

        bean.setModifytime(new Date());

        logger.debug("==========api/goods/modify 1289=" + JSON.toJSONString(bean));
        bean.setModifier(ObjectUtil.getUid());

        if (bean.getShareBonusType() != null && bean.getShareBonusType() == XffanType.qian.getVal()
                && bean.getShareMount() != null && bean.getShareMount().doubleValue() > 0 && bean.getType() >= 0
        ) {
            if (bean.getMinPrice() == null || bean.getMinPrice().add(bean.getShareMount()).doubleValue() > bean.getSaleprice().doubleValue())
                bean.setMinPrice(bean.getSaleprice().subtract(bean.getShareMount()));
        }

        logger.debug("==========api/goods/modify=" + JSON.toJSONString(bean));

        try {
            Goods goods = goodsService.selectById(bean.getId());
            if ((bean.getSaleprice() != null && goods.getSaleprice().doubleValue() != bean.getSaleprice().doubleValue())
                    || (bean.getShareBonusType() != null && goods.getShareBonusType() != bean.getShareBonusType())) {
                logger.debug("==============================api/goods/modify  1111");
                //平台入驻商家
                //非平台入驻商家，商家自营的，无需处理营销成本
                if (goods.getSid() != null && goods.getSid().longValue() > 0) {
                    if (bean.getSaleprice() != null && bean.getSaleprice().doubleValue() > 0) {
                        //【商品活动级别默认处理分润】
                        Mdpay mdpay = mdpayMapper.selectById(bean.getSid());
                        logger.debug("==============================api/goods/modify  222");

                        if (mdpay == null) {
                            Mdpay entity = new Mdpay();
                            entity.setMpid(goods.getMpid());
                            entity.setSid(-goods.getMpid());
                            mdpay = mdpayMapper.selectById(entity);
                        }
                        Store store = redisService.getStore(goods.getSid());
                        if (mdpay != null && store.getLeagueid() != null) {
                            //===待完善
                            //1、优先计算平台收款，保证平台成本，每单都有
                            bean.setPtfan(bean.getSaleprice().multiply(mdpay.getPayplat()));
                            //1、其次计算商家收款，保证商家成本，每单都有
                            bean.setLmfan(bean.getSaleprice().multiply(mdpay.getPaymeng()));

                            logger.debug("==============================api/goods/modify  333");

                            //3、最后计算分佣
                            if (bean.getShareBonusType() != null && bean.getShareBonusType() == XffanType.qian.getVal()
                                    && bean.getShareMount() != null && bean.getShareMount().doubleValue() > 0) {
                                logger.debug("==============================api/goods/modify  444");

                            } else {
                                logger.debug("==============================api/goods/modify  555");
                                bean.setShareMount(new BigDecimal(0));
                            }
                            bean.setMinPrice(bean.getSaleprice().subtract(bean.getPtfan()).subtract(bean.getLmfan()).subtract(bean.getShareMount()));

                            //===待完善
                            //矫正，如果审批实物，联盟利润为零,分享利润太高
                            if (bean.getLmfan().doubleValue() < 0) {
                                info.setCode(1);
                                info.setMsg("佣金分配不合理请重新设置");
                                return info;
                            }
                            logger.debug("==============================api/goods/modify  666");
                        } else {
                            //无联盟无代理模式分润
                            //活动商品成交价=商家收款+平台收佣+推荐人佣金
                            //该模式相对简单
                            //处理分佣
                            bean.setPtfan(bean.getSaleprice().multiply(mdpay.getPayplat()));
                            bean.setLmfan(new BigDecimal(0));

                            if (bean.getShareBonusType() != null && bean.getShareBonusType() == XffanType.qian.getVal()
                                    && bean.getShareMount() != null && bean.getShareMount().doubleValue() > 0) {

                            } else {
                                bean.setShareMount(new BigDecimal(0));
                            }
                            //商家入账
                            bean.setMinPrice(bean.getSaleprice().subtract(bean.getPtfan()).subtract(bean.getLmfan()).subtract(bean.getShareMount()));
                        }
                    }
                } else {
                    //非平台型，商家自营行
                    //minprice==针对入驻商家的成本
                    bean.setSid(null);
                    if (bean.getSaleprice() != null && bean.getSaleprice().doubleValue() > 0) {
                        if (bean.getShareBonusType() != null && bean.getShareBonusType() == XffanType.qian.getVal()
                                && bean.getShareMount() != null && bean.getShareMount().doubleValue() > 0) {
                            //校验
                            if (bean.getShareMount().doubleValue() > bean.getSaleprice().doubleValue()) {
                                info.setCode(1);
                                info.setMsg("佣金设置有误");
                                return info;
                            }

                            //非平台入驻商家，商家自营的，且有分享奖金+奖励模式是普通模式
                            if (bean.getFxmode() != null && bean.getFxmode() == Fxmode.common.getVal()) {
                                bean.setPtfan(bean.getSaleprice().subtract(bean.getShareMount()));
                            } else if (bean.getFxmode() != null && bean.getFxmode() == Fxmode.fexiao.getVal()) {
                                //非平台入驻商家，商家自营的，且有分享奖金+奖励模式是分销模式，在支付成功生成订单时处理
                            } else if (bean.getFxmode() != null && bean.getFxmode() == Fxmode.jieti.getVal()) {
                                //===待完善
                                //非平台入驻商家，商家自营的，且有分享奖金+奖励模式是阶梯模式
                            }
                        } else {
                            //没有设置佣金
                            bean.setPtfan(bean.getSaleprice());//商家自营行
                        }
                    }
                }
            }

            if (bean.getType() != null && bean.getType().intValue() > 0) {
                bean.setState(-1);
                bean.setStatus(Gstatus.shenhe.getVal());
            }
            Date start;
            Date end;
            Date now = new Date();
            try {
                start = DateUtil.toDate(dateStart);
                end = DateUtil.toDate(dateEnd);

                if (end.getTime() <= now.getTime()) {
                    info.setCode(1);
                    info.setMsg("活动结束日期有误");
                    return info;
                }
            } catch (Exception e) {
                logger.debug("date format error", e);
                info.setCode(1);
                info.setMsg("参数有误");
                return info;
            }

            bean.setStartDate(start);
            bean.setEndDate(end);
            bean.setCanyushu(null);

            bean.updateById();
            //更新素材资源
            AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                    .tell("Goods@" + bean.getId() + "@update", ActorRef.noSender());

            if (toupiao != null && toupiao.getDanripiao() != null) {
                toupiao.setGid(bean.getId());
                toupiao.setCreatetime(bean.getCreatetime());
                toupiao.updateById();
            }

            GoodsMusic goodsMusic = goodsMusicService.selectById(bean.getId());
            if (goodsMusic != null && bean.getMusicid() != null) {
                Music music = musicService.selectById(goodsMusic.getMusicid());
                if (music != null && bean.getMusicid() != music.getId()) {
                    goodsMusicService.deleteById(bean.getId());
                    goodsMusic = new GoodsMusic();
                    goodsMusic.setGid(bean.getId());
                    goodsMusic.setMusicid(bean.getMusicid());
                    goodsMusic.setMpid(ObjectUtil.getMpid());
                    goodsMusic.setCreatetime(new Date());
                    goodsMusic.insert();
                }
            }

            AkkaServer.system.actorOf(Props.create(StoreActor.class))
                    .tell(Constants.AKKA_MSG_GOODS_MODIFY + "@" + bean.getId(), ActorRef.noSender());

            Integer i = 0;
            String rkey = Constants.REDIS_GOODS_LIST + ObjectUtil.getMid() + "_" + ObjectUtil.getMpid() + "_" + bean.getCid() + "_";
            for (i = 0; i < 10; i++) {
                redisService.del(rkey + i.toString());
            }
        } catch (Exception e) {
            logger.error("=====/api/goods/modify updateById ", e);
        }

        return info;
    }

    @RequestMapping("/api/goods/getmusic")
    @ResponseBody
    public Jinfo getmusic(Long gid) {
        Jinfo info = new Jinfo();
        if (gid == null) {
            info.setCode(4);
            return info;
        }
        GoodsMusic goodsMusic = goodsMusicService.selectById(gid);

        if (goodsMusic != null) {
            Music music = musicService.selectById(goodsMusic.getMusicid());
            if (music == null) {
                info.setCode(4);
                return info;
            }
            Map map = new HashMap<String, String>();
            map.put("musicid", music.getId());
            map.put("musicname", music.getName());
            map.put("musicurl", music.getUrl());
            info.setInfo(map);
        }
        return info;
    }

    //活动商品删除
    @RequestMapping("/api/goods/delete")
    @ResponseBody
    public Jinfo delete(Long id) {

        Jinfo info = new Jinfo();
        //字段校验
        try {
            Goods goods = goodsService.selectById(id);

            if (goods == null) info.setCode(4);
            else if (ObjectUtil.getMpid() != goods.getMpid()) {
                info.setCode(1);
                info.setMsg("无权限删除");
            } else {
                Goods g = new Goods();
                g.setId(goods.getId());
                g.setIsDeleted(1);
                g.setState(-1);
                g.setStatus(-1);
                g.updateById();

                if (g.getSid() != null) {
                    StoreStat storeStat = storeStatMapper.selectById(g.getId());
                    if (storeStat == null) {
                        storeStat = new StoreStat();
                        storeStat.setStoreid(g.getId());
                    }
                    storeStat.setGoods(storeStat.getGoods() - 1);
                    storeStat.updateById();
                }
            }
        } catch (Exception e) {
            logger.error("=====/api/goods/modify detailbyid ", e);
        }

        return info;
    }

    @RequestMapping("/api/goods/detailbyid")
    @ResponseBody
    public Jinfo detailbyid(Long gid) {

        Jinfo info = new Jinfo();
        //字段校验
        try {
            Goods goods = goodsService.selectById(gid);
            if (goods == null) info.setCode(4);
            else info.setInfo(goods);
        } catch (Exception e) {
            logger.error("=====/api/goods/modify detailbyid ", e);
        }

        return info;
    }

    @RequestMapping("/api/goods/yxdetail")
    @ResponseBody
    public Jinfo yxdetail(String gid,
                          @RequestParam(value = "oid", required = false) String ooid,
                          @RequestParam(value = "userinfo", required = false) Integer userinfo,
                          @RequestParam(value = "ptoid", required = false) Long ptoid
    ) {
        Jinfo info = new Jinfo();
        Long oid = null;
        if (!Strings.isNullOrEmpty(ooid)) {
            try {
                oid = Long.valueOf(ooid);
            } catch (NumberFormatException e) {
//                logger.error("ooid error",e);
            }
        }
        Long uid = ObjectUtil.getUid();
        if (Strings.isNullOrEmpty(gid) || Strings.isNullOrEmpty(gid.replace("undefined", ""))) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }
        //字段校验
        try {
            Long lgid = Long.parseLong(gid);
            Goods goods = goodsService.selectById(lgid);
            if (goods == null) {
                info.setCode(4);
                return info;
            }
            if (goods.getSid() == null) {
                info.setInfo(goods);
                return info;
            }

            //浏览次数更新
            AkkaServer.system.actorOf(Props.create(GoodsActor.class))
                    .tell(Constants.AKKA_MSG_GOODS_VIEW + "@" + goods.getId(), ActorRef.noSender());
            //商家信息
            Store store = storeService.selectById(goods.getSid());

            //商家浏览次数更新
            if (store != null) {
                AkkaServer.system.actorOf(Props.create(StoreActor.class))
                        .tell(Constants.AKKA_MSG_STORE_VIEW + "@" + store.getId(), ActorRef.noSender());
            }
            goods.setStore(store);

            //活动收藏
            int cout = uid == null ? 0 : goodsfavService.selectCount(new EntityWrapper<Goodsfav>().eq("gid", goods.getId())
                    .eq("uid", uid).eq("state", 1).eq("type", 1));
            goods.setShoucang(cout == 1);

            //店铺收藏
            cout = uid == null || store == null ? 0 : goodsfavService.selectCount(new EntityWrapper<Goodsfav>().eq("gid", store.getId())
                    .eq("uid", uid).eq("state", 1).eq("type", 2));
            goods.setDpshoucang(cout == 1);

            //是否是案例
            int ishdtpl = hdtemplateService.selectCount(new EntityWrapper<Hdtemplate>().eq("gid", gid));
            goods.setIshdtpl(ishdtpl >= 1);

            //参与情况
            if (goods.getType() == YXType.pintuan.getVal()) {
                if (ptoid == null && oid != null) {
                    PintuanLog ptl = pintuanLogService.selectOne(new EntityWrapper<PintuanLog>()
                            .eq("oid", oid));
                    ptoid = ptl.getPtoid();
                }

                //团购活动详情页面
                List<PintuanOpen> pintuan = null;
                if (ptoid == null) {
                    Page page = new Page(1, 3);
                    pintuan = pintuanOpenService.selectPage(page, new EntityWrapper<PintuanOpen>()
                            .eq("gid", goods.getId()).eq("state", 1)
                            .eq("status", PTstatus.init.getVal()).orderBy("pnumber", false)).getRecords();

                } else {
                    pintuan = pintuanOpenService.selectList(new EntityWrapper<PintuanOpen>()
                            .eq("id", ptoid));
                }
                for (PintuanOpen item : pintuan) {
                    item.setPhone(goodsService.replaceXing(item.getPhone()));
                }
                goods.setPintuan(pintuan);
                List<PintuanLog> tuanyuan = pintuanLogService.selectList(new EntityWrapper<PintuanLog>()
                        .setSqlSelect(" distinct uid,avatarpic ")
                        .eq("gid", goods.getId()).eq("state", 1));
                goods.setTuanyuan(tuanyuan);

                if (userinfo != null && userinfo == 1) {
                    //开团页面
                    List<PintuanLog> pinlist = pintuanLogService.selectList(
                            new EntityWrapper<PintuanLog>().eq("ptoid", ptoid)
                                    .eq("state", 1)
                                    .orderBy("id")
                    );
                    goods.setIsme(false);
                    if (uid != null) {
                        for (PintuanLog item : pinlist) {
                            if (item.getUid().longValue() == uid.longValue()) goods.setIsme(true);
                        }
                    }
                    logger.info("------------------ptoid=" + ptoid + " pintuan pinlist=" + JSON.toJSONString(pinlist));
                    info.setExtra(pinlist);
                }
            } else if (goods.getType() == YXType.kanjia.getVal()) {
                Page page = new Page(1, 200);
                List<CutpriceHelp> kanyuan = cutpriceHelpService.selectPage(page, new EntityWrapper<CutpriceHelp>()
                        .setSqlSelect("distinct uid,avatarpic,cutprice ")
                        .eq("gid", goods.getId()).orderBy("cutprice", false)).getRecords();
                goods.setKanyuan(kanyuan);

                List<CutpriceHelp> kanyuanbang = cutpriceHelpService.selectPage(page, new EntityWrapper<CutpriceHelp>()
                        .eq("gid", goods.getId()).orderBy("cutprice", false)).getRecords();
                goods.setKanyuanbang(kanyuanbang);

                if (oid != null) {
                    logger.info("------------------ptoid==null&&oid!=null oid=" + oid);
                    CutpriceOpen co = cutpriceOpenService.selectOne(new EntityWrapper<CutpriceOpen>()
                            .eq("oid", oid));
                    ptoid = co.getId();
                    List<CutpriceHelp> cutlist = cutpriceHelpService.selectList(new EntityWrapper<CutpriceHelp>()
                            .setSqlSelect("distinct uid,avatarpic,cutprice,nickname,createtime,isnew")
                            .eq("coid", ptoid).orderBy("id"));
                    co.setCutlist(cutlist);
                    goods.setKanjia(co);
                }
//                else {
//                    logger.info("------------------ptoid!=null ptoid=" + ptoid);
//                    CutpriceOpen co = cutpriceOpenService.selectOne(new EntityWrapper<CutpriceOpen>()
//                            .eq("id", ptoid));
//                    List<CutpriceHelp> cutlist = cutpriceHelpService.selectList(new EntityWrapper<CutpriceHelp>()
//                            .setSqlSelect("distinct uid,avatarpic,cutprice,nickname,createtime ")
//                            .eq("coid", ptoid).orderBy("id"));
//                    co.setCutlist(cutlist);
//                    goods.setKanjia(co);
//                }

                if (ptoid != null && goods.getKanjia() != null) {
                    int cutcout = cutpriceHelpService.selectCount(new EntityWrapper<CutpriceHelp>()
                            .eq("coid", ptoid).eq("uid", uid));
                    if (cutcout > 0) {
                        goods.getKanjia().setHasCut(true);
                    } else {
                        goods.getKanjia().setHasCut(false);
                    }
                }

                if (ObjectUtil.getUid() != null &&
                        goods.getKanjia() != null && goods.getKanjia().getUid().longValue() == ObjectUtil.getUid().longValue()) {
                    goods.setIsme(true);
                } else {
                    goods.setIsme(false);
                }
                // 神秘礼品
                if (!Strings.isNullOrEmpty(goods.getXmtype())) {
                    Goods liping = goodsService.selectOne(new EntityWrapper<Goods>().setSqlSelect("id,name")
                            .eq("id", goods.getXmtype()));
                    if (liping != null) {
                        Map<String, Object> smliping = new HashMap<String, Object>();
                        smliping.put("gid", liping.getId());
                        smliping.put("gname", liping.getName());
                        goods.setSmliping(smliping);
                    }
                }
            } else if (goods.getType() == YXType.choujiang.getVal() && userinfo == null) {
                Order order = orderService.selectById(oid);
                goods.setOrder(order);
                List<ChoujiangLog> jzusers = choujiangLogService.selectList(new EntityWrapper<ChoujiangLog>()
                        .setSqlSelect(" distinct uid,avatarpic ")
                        .eq("gid", goods.getId()));
                //抽奖人员
                goods.setCjusers(jzusers);

                //一期固定四个奖品或八个奖品
                List<Choujiang> jiangpins = choujiangService.selectList(new EntityWrapper<Choujiang>()
                        .eq("gid", goods.getId())
                        .orderBy("level")
                );
                List<Choujiang> alljiangpins = new ArrayList<>();
                if (jiangpins != null && jiangpins.size() < 8) {
                    for (Choujiang item : jiangpins) {
                        alljiangpins.add(item);
                        Choujiang kong = new Choujiang();
                        kong.setJtype(5);
                        kong.setName("谢谢参与");
                        alljiangpins.add(kong);
                    }
                    if (alljiangpins.size() < 8) {
                        for (int i = 0; i < 8 - alljiangpins.size(); i++) {
                            Choujiang kong = new Choujiang();
                            kong.setJtype(5);
                            kong.setName("谢谢参与");
                            alljiangpins.add(kong);
                        }
                    }
                } else {
                    alljiangpins = jiangpins;
                }
                //设置奖品
                goods.setJiangpins(alljiangpins);

                //是否已报名购买
                int hasbuy = uid == null ? 0 : orderService.selectCount(new EntityWrapper<Order>()
                        .eq("uid", uid).eq("gid", gid).eq("status", 2));//已付费参与
                goods.setHasbuy(hasbuy);
                //今日抽奖数
                int cjshu = uid == null ? 0 : choujiangLogService.selectCount(new EntityWrapper<ChoujiangLog>()
                        .eq("uid", uid).eq("gid", gid).eq("cjdate", DateUtil.getToday()));
                goods.setCjshu(cjshu);

                //活动总中奖数：ptotal
                //个人中奖数：ptotal
                int iszhong = uid == null ? 0 : choujiangLogService.selectCount(new EntityWrapper<ChoujiangLog>()
                        .eq("uid", uid).eq("gid", gid).eq("is_zhong", 1));
                goods.setIszhong(iszhong);

                //今日抽奖群分享
                int todayshare = uid == null ? 0 : shareService.selectCount(new EntityWrapper<Share>()
                        .eq("uid", ObjectUtil.getUid())
                        .eq("sharedate", DateUtil.getToday())
                        .eq("ywid", gid)
                );
                goods.setTodayshare(todayshare);

                //中奖记录人数
                List<ChoujiangLog> zlist = choujiangLogService.selectList(
                        new EntityWrapper<ChoujiangLog>().eq("gid", gid)
                                .eq("is_zhong", 1)
                                .orderBy("level")
                );
                for (ChoujiangLog item : zlist) {
                    if (!Strings.isNullOrEmpty(item.getPhone()))
                        item.setPhone(goodsService.replaceXing(item.getPhone()));
                }
                info.setExtra(zlist);
                //参与人数
                List<Order> olist = orderService.selectList(new EntityWrapper<Order>().setSqlSelect("distinct uid ")
                        .gt("status", 1)
                        .eq("state", 1)
                        .eq("gid", gid));
                if (olist != null && olist.size() > 0) {
                    List<Long> uids = new ArrayList<>();
                    for (Order o : olist) {
                        uids.add(o.getUid());
                    }
                    List<User> ulist = userService.selectList(new EntityWrapper<User>()
                            .setSqlSelect("id,avatar_pic avatarPic,nick_name nickName,phone")
                            .in("id", uids));
                    goods.setUsers(ulist);
                }
                //======参与人数End=====

                //用户购买订单
                if (uid != null && oid == null) {
                    goods.setOrder(orderService.selectOne(new EntityWrapper<Order>()
                            .setSqlSelect("id,status,goods_number goodsNumber")
                            .eq("status", 2)
                            .eq("uid", uid).eq("gid", gid)));
                }
            } else if (goods.getType() == YXType.jizan.getVal()) {
                if (userinfo == null) {
                    //活动详情页面
                    List<JizanLog> jzusers = jizanLogService.selectList(new EntityWrapper<JizanLog>()
                            .setSqlSelect(" distinct uid,avatarpic ").eq("gid", gid).eq("state", 1));
                    goods.setJzusers(jzusers);//集赞参与用户
//                    info.setExtra(jzusers);//当前活动用户
                }
                goods.setIsme(false);
                goods.setHasbuy(0);
                if (oid != null) {
                    //开团页面
                    Order order = orderService.selectById(oid);
                    goods.setOrder(order);
                    List<JizanLog> jzlist = jizanLogService.selectList(
                            new EntityWrapper<JizanLog>().eq("oid", oid)
                                    .eq("state", 1)
                                    .orderBy("id")
                    );
                    if (uid != null) {
                        for (JizanLog item : jzlist) {
                            item.setPhone(goodsService.replaceXing(item.getPhone()));
                            if (item.getUid().longValue() == uid.longValue()) goods.setIsme(true);
                        }
                    }
                    info.setExtra(jzlist);//当前活动参与

                } else if (uid != null) {
                    //是否已报名购买
                    int hasbuy = orderService.selectCount(new EntityWrapper<Order>()
                            .eq("uid", uid).eq("gid", gid).ge("status", 2).le("status", 3));
                    if (hasbuy > 0) {
                        goods.setHasbuy(1);
                        Order order = orderService.selectOne(new EntityWrapper<Order>()
                                .eq("uid", uid).eq("gid", gid).ge("status", 2).le("status", 3));
                        goods.setOrder(order);
                        oid = order.getId();
                        List<JizanLog> jzlist = jizanLogService.selectList(
                                new EntityWrapper<JizanLog>().eq("oid", oid)
                                        .eq("state", 1)
                                        .orderBy("id")
                        );
                        for (JizanLog item : jzlist) {
                            item.setPhone(goodsService.replaceXing(item.getPhone()));
                            if (item.getUid().longValue() == uid.longValue()) goods.setIsme(true);
                        }
                        info.setExtra(jzlist);//当前活动参与
                    }
                }

            } else if (goods.getType() == YXType.miaosha.getVal() && userinfo == null) {
                List<Order> olist = orderService.selectList(new EntityWrapper<Order>().setSqlSelect("distinct uid ")
                        .eq("state", 1).eq("gid", gid));
                if (olist != null && olist.size() > 0) {
                    List<Long> uids = new ArrayList<>();
                    for (Order o : olist) {
                        uids.add(o.getUid());
                    }
                    List<User> ulist = userService.selectList(new EntityWrapper<User>()
                            .setSqlSelect("id,avatar_pic avatarPic,nick_name nickName,phone").in("id", uids));
                    goods.setUsers(ulist);
                }

                olist = orderService.getOrdersBygid(lgid, 20, 1);
                for (Order item : olist) {
                    item.setPhone(goodsService.replaceXing(item.getPhone()));
                }
                goods.setOrders(olist);
            } else if (goods.getType() == YXType.dalibao.getVal() && userinfo == null) {
                List<Order> olist = orderService.selectList(new EntityWrapper<Order>().setSqlSelect("distinct uid ")
                        .eq("state", 1).eq("gid", gid));
                if (olist != null && olist.size() > 0) {
                    List<Long> uids = new ArrayList<>();
                    for (Order o : olist) {
                        uids.add(o.getUid());
                    }
                    List<User> ulist = userService.selectList(new EntityWrapper<User>()
                            .setSqlSelect("id,avatar_pic avatarPic,nick_name nickName,phone").in("id", uids));
                    goods.setUsers(ulist);
                }

                olist = orderService.getOrdersBygid(lgid, 20, 1);
                for (Order item : olist) {
                    item.setPhone(goodsService.replaceXing(item.getPhone()));
                }
                goods.setOrders(olist);

                List<String> quans = Arrays.asList(goods.getQuans().split(";"));
                info.setExtra(couponTplService.selectList(new EntityWrapper<CouponTpl>().in("id", quans)));

//                if (userinfo != null && userinfo == 1) {
//                    List<Coupon> quanlist = couponService.getStoreCoupon(uid, oid);
//                    info.setExtra(quanlist);
//                }
            } else if (goods.getType() == YXType.toupiao.getVal() && userinfo == null) {
                //投票
                List<Order> plist = orderService.selectList(new EntityWrapper<Order>()
                        .setSqlSelect("id,linkman,phone,headimg,goods_number goodsNumber,remark,service_code serviceCode")
                        .eq("state", 1).eq("gid", gid).orderBy("goods_number", false));
                plist = goodsService.calcLastpiao(plist);
                Map<String, Integer> paimingMap = goodsService.calcPaiming(plist);
                Map<String, Integer> lastpiaoMap = goodsService.calcLastpiaoMap(plist);
                List<Order> toplist = new ArrayList<Order>();
                List<Order> pxlist = new ArrayList<Order>();

                for (int i = 0; i < 3 && i <= plist.size() - 1; i++) {
                    toplist.add(plist.get(i));
                }
                for (int i = 3; i < plist.size() && plist.size() > 3; i++) {
                    pxlist.add(plist.get(i));
                }
                goods.setToporders(toplist);
                goods.setPxorders(pxlist);

                List<Order> olist = orderService.selectList(new EntityWrapper<Order>()
                        .setSqlSelect("id,uid,linkman,phone,headimg,goods_number goodsNumber,remark,service_code serviceCode")
                        .eq("gid", gid).orderBy("id", false));
                goods.setIsme(false);

                olist = goodsService.setLastpiaoMap(olist, lastpiaoMap);
                olist = goodsService.setPaiming(olist, paimingMap);
                int i = 0;
                for (Order item : olist) {
                    item.setPhone(goodsService.replaceXing(item.getPhone()));
                    if (uid != null && uid.longValue() == item.getUid().longValue()) {
                        goods.setIsme(true);
                        goods.setPtotal(i);
                    }
                    i++;
                }
                goods.setOrders(olist);

                List<ToupiaoLog> ulist = toupiaoLogMapper.selectList(new EntityWrapper<ToupiaoLog>().setSqlSelect("distinct uid ")
                        .eq("gid", gid));
                if (ulist != null && ulist.size() > 0) {
                    List<Long> uids = new ArrayList<>();
                    for (ToupiaoLog o : ulist) {
                        uids.add(o.getUid());
                    }
                    List<User> users = userService.selectList(new EntityWrapper<User>()
                            .setSqlSelect("id,avatar_pic avatarPic,nick_name nickName,phone").in("id", uids));
                    goods.setUsers(users);
                }
            } else if (goods.getType() == YXType.baoming.getVal()) {
                List<Order> olist = orderService.selectList(new EntityWrapper<Order>().setSqlSelect("distinct uid ")
                        .gt("status", 1)
                        .eq("state", 1)
                        .eq("gid", gid));
                if (olist != null && olist.size() > 0) {
                    List<Long> uids = new ArrayList<>();
                    for (Order o : olist) {
                        uids.add(o.getUid());
                    }
                    List<User> ulist = userService.selectList(new EntityWrapper<User>()
                            .setSqlSelect("id,avatar_pic avatarPic,nick_name nickName,phone")
                            .in("id", uids));
                    goods.setUsers(ulist);
                }

                if (userinfo == null) {
                    olist = orderService.getOrdersBygid(lgid, 20, 1);
                    for (Order item : olist) {
                        item.setPhone(goodsService.replaceXing(item.getPhone()));
                    }
                    goods.setOrders(olist);
                }
            }

            //开团页面处理限购+电话联系人+已购买数量
            if (userinfo != null && userinfo == 1 && uid != null) {
                User user = userService.selectOne(new EntityWrapper<User>()
                        .setSqlSelect("phone")
                        .eq("id", uid));
                if (user != null && !Strings.isNullOrEmpty(user.getPhone())) {
                    goods.setPhone(user.getPhone());
                    Order order = orderService.selectOne(new EntityWrapper<Order>()
                            .setSqlSelect("linkman").eq("mpid", ObjectUtil.getMpid())
                            .eq("uid", uid).isNotNull("linkman"));
                    goods.setLinkman(order == null ? null : order.getLinkman());
                }
                if (goods.getXiangou() != null && goods.getXiangou() > 0) {
                    Wrapper<Order> entity = new EntityWrapper<Order>()
                            .setSqlSelect(" sum(goods_number) goodsNumber")
                            .eq("mpid", ObjectUtil.getMpid())
                            .eq("gid", goods.getId())
                            .eq("state", 1)
                            .eq("uid", uid);

                    if (goods.getType() == YXType.kanjia.getVal()) entity.ge("status", 1);
                    else entity.ge("status", 2);

                    Order order = orderService.selectOne(entity);

                    if (order != null && order.getGoodsNumber() != null) goods.setMygou(order.getGoodsNumber());
                    logger.info("--------------------------------------goods.getMygou=" + goods.getMygou());
                }
            }
            //添加背景音乐
            GoodsMusic goodsMusic = goodsMusicService.selectById(goods.getId());
            if (goodsMusic != null) {
                Music music = musicService.selectById(goodsMusic.getMusicid());
                goods.setMusicurl(music.getUrl());
                goods.setMusicid(music.getId());
            }
            User user = redisService.getUser();
            if (user != null && user.getIsAgent() != null && user.getIsAgent() == 1) {
                goods.setAgent(true);
            }
            info.setInfo(goods);
        } catch (Exception e) {
            logger.error("=====/api/goods/yxdetail error ", e);
            info.setCode(1);
            info.setMsg("参数有误");
        }


        return info;
    }

    //营销朋友圈海报
    @RequestMapping("/api/goods/pyq")
    @ResponseBody
    public Jinfo pyq(String page, String ywid,
                     @RequestParam(value = "oid", required = false) String oid,
                     @RequestParam(value = "color", required = false) String color,
                     @RequestParam(value = "type", required = false) Integer type,
                     @RequestParam(value = "width", required = false) Integer width,
                     @RequestParam(value = "rpage", required = false) String rpage
    ) {
        Jinfo info = new Jinfo();

        MerchantApp mapp = redisService.getMApp();
        String path = Constants.WX_MQR_PATH.replace("MCODE", mapp.getMcode()).replace("MPCODE", mapp.getMpcode());
        HttpUtil.checkDirectory(path);
        if (ObjectUtil.getUid() == null) {
            info.setCode(1);
            info.setMsg("请授权登录后再进行此操作");
            return info;
        }
        path = path + ObjectUtil.getUid() + "_" + page + "_" + ywid + ".png";
        rpage = Strings.isNullOrEmpty(rpage) ? "pages" : rpage;

        String uid = ObjectUtil.getUid().toString();
        //String scene //uid+page+act+ywid 方式一
        //String scene = uid+oid+type+gid  方式二;用户营销活动海报
//        String scene = Strings.isNullOrEmpty(oid) ? (uid + "_" + Constants.PAGE_MAP.get(page) + "_Q_" + ywid)
        String scene = Strings.isNullOrEmpty(oid) ? (uid + "__Q_" + ywid)
                : (uid + "_" + oid + "_" + type + "_" + ywid);
        //统一用无限制带参二维码
        page = rpage + "/" + page + "/" + page;
        logger.debug("========================================api/goods/pyq page=" + page);
        logger.debug("========================================api/goods/pyq scene=" + scene);
        if (width == null) width = 160;
        String qr = HttpUtil.getminiQr(redisService.getWxtoken(), path, page, scene, 160, false, color, true);
        logger.debug("==========qr=" + qr);
        info.setInfo(qr);
        return info;
    }

    private boolean matchStart(List<String> list, String str) {
        boolean flag = false;
        for (String item : list) {
            if (item.startsWith(str)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    private String appendArr(String[] arr, int m) {
        if (m == 0) return arr[0];
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i <= m; i++) {
            if (i == m) sb.append(arr[i]);
            else sb.append(arr[i] + "_");
        }
        return sb.toString();
    }


    @RequestMapping("/test/goods/init15")
    @ResponseBody
    public Jinfo init15(@RequestParam("hkyid") long id) {
        Jinfo json = new Jinfo();
        try {
            List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", 11).eq("sid", 2));
            List<GoodsSku> skulist = goodsSkuService.selectList(new EntityWrapper<GoodsSku>().eq("mpid", 11).eq("sid", 2).orderBy("id", true));

//           List<Goods> slist = goodsService.selectList(new EntityWrapper<Goods>().eq("mid", 20).isNotNull("sid").ne("sid", 2));

            Map<String, Goods> map = new HashMap<String, Goods>();

            for (Goods item : list) {
                map.put("cid_" + item.getCid().toString(), item);
            }

            List<Store> storelist = storeService.selectList(new EntityWrapper<Store>().eq("mpid", 11).ne("id", 2));
            Map<String, GoodsSku> skumap = new HashMap<String, GoodsSku>();

            for (Store item : storelist) {
                for (Goods gitem : list) {
                    gitem.setId(null);
                    gitem.setSid(item.getId());
                    gitem.insert();

                    if (gitem.getCid() == 139) {
                        for (GoodsSku skitem : skulist) {
                            skitem.setId(null);
                            skitem.setGid(gitem.getId());
                            skitem.setSid(item.getId());
                            skitem.insert();
                        }
                    }
                }

            }

        } catch (Exception e) {
            logger.error("======test/goods/init15 error", e);
            json.setCode(5);
        }
        return json;
    }

    @RequestMapping("/test/goods/fixmpidgoods")
    @ResponseBody
    public Jinfo fixmpidgoods(@RequestParam("hkyid") long id) {
        Jinfo json = new Jinfo();
        try {
            List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mid", 15).eq("mpid", 5));

            for (Goods item : list) {
                item.setId(null);
                item.setMpid(17l);
                item.insert();
            }

        } catch (Exception e) {
            logger.error("======api/goods/initzhensuoimg error", e);
            json.setCode(5);
        }
        return json;
    }

    @RequestMapping("/test/goods/initsku15")
    @ResponseBody
    public Jinfo initsku15(@RequestParam("hkyid") long id) {
        Jinfo json = new Jinfo();
        try {
            List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", 11).eq("cid", 139));

            List<Goods> yangpin = new ArrayList<Goods>();
            Goods goods = new Goods();
            goods.setName("超声波洁牙");
            goods.setSaleprice(new BigDecimal(80));
            goods.setPrice(new BigDecimal(80));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("气动舒适洁牙");
            goods.setSaleprice(new BigDecimal(150));
            goods.setPrice(new BigDecimal(150));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("高清深度洁牙");
            goods.setSaleprice(new BigDecimal(200));
            goods.setPrice(new BigDecimal(200));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("牙周治疗仪");
            goods.setSaleprice(new BigDecimal(380));
            goods.setPrice(new BigDecimal(380));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("喷砂");
            goods.setSaleprice(new BigDecimal(80));
            goods.setPrice(new BigDecimal(80));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("牙齿抛光");
            goods.setSaleprice(new BigDecimal(30));
            goods.setPrice(new BigDecimal(30));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("牙齿脱敏抛光");
            goods.setSaleprice(new BigDecimal(50));
            goods.setPrice(new BigDecimal(50));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("CBCT");
            goods.setSaleprice(new BigDecimal(200));
            goods.setPrice(new BigDecimal(200));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("牙齿清洁套餐【超声洁牙+喷砂+抛光+牙周药浴】");
            goods.setSaleprice(new BigDecimal(168));
            goods.setPrice(new BigDecimal(190));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("舒适保健套餐【气动舒适洁牙+喷砂+牙齿脱敏抛光+牙周药浴】");
            goods.setSaleprice(new BigDecimal(248));
            goods.setPrice(new BigDecimal(280));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("牙周护理套餐【高清深度洁牙+牙齿脱敏抛光+漱口水+牙周药浴】");
            goods.setSaleprice(new BigDecimal(260));
            goods.setPrice(new BigDecimal(290));
            yangpin.add(goods);

            goods = new Goods();
            goods.setName("牙周治疗套餐【牙周治疗仪+牙周药物治疗+漱口水】");
            goods.setSaleprice(new BigDecimal(560));
            goods.setPrice(new BigDecimal(600));
            yangpin.add(goods);


            for (Goods item : list) {
                for (Goods yp : yangpin) {

                    GoodsSku goodssku = new GoodsSku();
                    goodssku.setName(yp.getName());
                    goodssku.setPrice(yp.getPrice());
                    goodssku.setSaleprice(yp.getSaleprice());
                    goodssku.setCid(item.getCid());
                    goodssku.setGid(item.getId());
                    goodssku.setSid(item.getSid());

                    goodssku.setPic(item.getPic());

                    goodssku.setState(1);
                    goodssku.setGtype(3);
                    goodssku.setType(0);
                    goodssku.setMid(20l);
                    goodssku.setMpid(11l);

                    goodssku.insert();
                }
            }
        } catch (Exception e) {
            logger.error("======api/goods/initsku15 error", e);
            json.setCode(5);
        }
        return json;
    }

    //复制案例活动接口(活动克隆接口)
    //param gid:活动ID
    //param extval:微信字段
    //param dateStart:活动ID(2020-02-02 02:01:00)
    //param dateEnd:结束日期(2020-02-02 02:02:59)
    //param sid:商家ID
    @RequestMapping("/api/goods/fuzhi")
    @ResponseBody
    public Jinfo fuzhi(Long gid, String dateStart, String dateEnd, String extval, Long sid) {
        Jinfo info = new Jinfo();
        logger.debug("-------------------------goods/fuzhi gid=" + gid);
        logger.debug("-------------------------goods/fuzhi dateStart=" + dateStart);
        logger.debug("-------------------------goods/fuzhi dateEnd=" + dateEnd);
        logger.debug("-------------------------goods/fuzhi extval=" + extval);
        logger.debug("-------------------------goods/fuzhi sid=" + sid);

        Goods goods = goodsMapper.selectById(gid);
        if (goods == null || Strings.isNullOrEmpty(dateStart) || Strings.isNullOrEmpty(dateEnd)) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }
        Date start;
        Date end;
        Date now = new Date();
        try {
            start = DateUtil.toDate(dateStart);
            end = DateUtil.toDate(dateEnd);

            if (end.getTime() <= now.getTime()) {
                info.setCode(1);
                info.setMsg("活动结束日期有误");
                return info;
            }
        } catch (Exception e) {
            logger.debug("date format error", e);
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }

        User user = redisService.getUser();
        if (user.getIsMch() != 1 && user.getIsAgent() != 1 && user.getIsPlatform() != 1) {
            info.setCode(1);
            info.setMsg("无权限操作");
            return info;
        }
        if (sid == null) {
            sid = ObjectUtil.getSid();
        }
        if (sid == null) {
            info.setCode(1);
            info.setMsg("当前用户非商户");
            return info;
        }
        Store store = storeService.selectById(sid);

        if (store == null || store.getState() != 1) {
            info.setCode(1);
            info.setMsg("当前商户不存在或已下线");
            return info;
        }

        goods.setId(null);
        goods.setSid(sid);
        if (store.getLeagueid() != null) goods.setLeagueid(store.getLeagueid());
        goods.setExtval(extval);
        goods.setStartDate(start);
        goods.setEndDate(end);

        //状态
        goods.setState(1);
        goods.setStatus(1);//待审核

        int stores = goods.getNumberSale() + goods.getStores();
        //清零
        goods.setNumberFav(0);
        goods.setNumberGrade(0);
        goods.setNumberSale(0);
        goods.setNumberOrders(0);
        goods.setCanyushu(0);
        goods.setHexiaoshu(0);
        goods.setFxjiangshu(0);
        goods.setViews(0);

        if (goods.getType() == YXType.choujiang.getVal()) goods.setPtotal(0);

        goods.setCreatetime(now);
        goods.setUid(ObjectUtil.getUid());
        goods.setModifier(null);
        goods.setModifytime(null);

        goods.insert();

        logger.debug("======api/goods/fuzhi goodsMusic start");
        //处理音乐，复制
        GoodsMusic goodsMusic = goodsMusicService.selectById(gid);
        if (goodsMusic != null) {
            goodsMusic.setGid(goods.getId());
            goodsMusic.setCreatetime(new Date());
            goodsMusic.insert();
            logger.debug("======api/goods/fuzhi goodsMusic ok");
        }

        //处理商品活动--商家关联
        List<GoodsStore> goodsStoreList = goodsStoreMapper.selectList(new EntityWrapper<GoodsStore>().eq("gid", gid));
        if (goodsStoreList != null && goodsStoreList.size() > 0) {
            for (GoodsStore item : goodsStoreList) {
                item.setId(null);
                item.setGid(goods.getId());
                item.setCreatetime(new Date());
                item.insert();
            }
            logger.debug("======api/goods/fuzhi GoodsStore ok");
        }

        //处理关联奖品，复制
        Goods ngoods = new Goods();
        ngoods.setId(goods.getId());
        logger.debug("======api/goods/fuzhi goodsMusic choujiang start");
        if (goods.getType() == YXType.choujiang.getVal()) {
            List<Choujiang> cjlist = choujiangService.selectList(new EntityWrapper<Choujiang>().eq("gid", gid));
            for (Choujiang item : cjlist) {
                item.setGid(goods.getId());
                item.setSid(sid);
                item.setId(null);
                item.insert();
                stores += item.getNum();
            }
            ngoods.setStores(stores);
            logger.debug("======api/goods/fuzhi goodsMusic choujiang OK");
        } else if (goods.getType() == YXType.dalibao.getVal() && !Strings.isNullOrEmpty(goods.getQuans())) {
//            List<String> quanids = Arrays.asList(goods.getQuans().split(";"));
            ngoods.setQuans("");
            ngoods.setStores(stores);
        } else {
            ngoods.setStores(stores);
        }
        ngoods.updateById();

        return info;
    }

    //xgkucun
    @RequestMapping("/api/goods/xgkucun")
    @ResponseBody
    public Jinfo xgkucun(Goods goods) {
        Jinfo json = new Jinfo();
        if (goods.getId() == null) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }
        if (goods.getHyprice() != null && goods.getHyprice().doubleValue() == 0) goods.setHyprice(null);
        goods.setModifytime(new Date());
        goods.setModifier(ObjectUtil.getUid());

        //修改各种佣金返
        Goods g = goodsService.selectById(goods.getId());
        Long mpid = g.getMpid();
        int cout = mdpayMapper.selectCount(new EntityWrapper<Mdpay>().eq("sid", -mpid).eq("mpid", mpid));
        if (g.getSid() != null && cout > 0) {
            Mdpay mdpay = mdpayMapper.selectById(g.getSid());
            if (mdpay != null) {
                goods.setMinPrice(goods.getSaleprice().multiply(mdpay.getPaymch()));
                goods.setShareMount(goods.getSaleprice().multiply(mdpay.getPayshare()));
                goods.setLmfan(goods.getSaleprice().multiply(mdpay.getLeagueid() == null ? new BigDecimal(0) : mdpay.getPaymeng()));
                goods.setPtfan(goods.getSaleprice().subtract(goods.getShareMount()).subtract(goods.getLmfan()).subtract(goods.getMinPrice()));
            }
        }

        goods.updateById();
        return json;
    }

    //==================================================
    //==================private method==================
    //添加商品
    @RequestMapping("/api/goods/add")
    @ResponseBody
    public Jinfo save(Goods bean, GoodsToupiao toupiao,
                      String jps) {
        logger.debug("====================api/goods/add" + JSON.toJSONString(bean));
        Jinfo info = new Jinfo();
        if (ObjectUtil.getUid() == null) {
            info.setCode(1);
            info.setMsg("请授权登录之后再进行相关操作");
            return info;
        }

        bean.setCreatetime(new Date());
        bean.setModifytime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());

        User user = userService.selectById(ObjectUtil.getUid());
        if (bean.getSid() == null) bean.setSid(user.getSid());//设置SID[0]
        //设置SID[0]
        if (user.getSid() != null) bean.setLeagueid(redisService.getLeagueid(user.getSid()));
        bean.setUid(ObjectUtil.getUid());
        if (bean.getCid() == null) bean.setCid(0l);
        if (bean.getShareMount() == null) bean.setShareMount(new BigDecimal(0));

        //开始日期，结束日期
        String dateStart = bean.getDateStart();
        String dateEnd = bean.getDateEnd();

        //date_start
        if (!Strings.isNullOrEmpty(dateStart) && dateStart.trim().length() == 10) {
            dateStart += " 00:00:00";
            bean.setStartDate(DateUtil.toDate(dateStart));
        } else if (!Strings.isNullOrEmpty(bean.getDateStart()) && bean.getDateStart().trim().length() == 16) {
            dateStart += ":00";
            bean.setStartDate(DateUtil.toDate(dateStart));
        } else if (!Strings.isNullOrEmpty(bean.getDateStart()) && bean.getDateStart().trim().length() == 19) {
            bean.setStartDate(DateUtil.toDate(dateStart));
        }

        //date_end
        if (!Strings.isNullOrEmpty(dateEnd) && dateEnd.trim().length() == 10) {
            dateEnd += " 23:59:59";
            bean.setEndDate(DateUtil.toDate(dateEnd));
        } else if (!Strings.isNullOrEmpty(dateEnd) && dateEnd.trim().length() == 16) {
            dateEnd += ":00";
            bean.setEndDate(DateUtil.toDate(dateEnd));
        } else if (!Strings.isNullOrEmpty(dateEnd) && dateEnd.trim().length() == 19) {
            bean.setEndDate(DateUtil.toDate(dateEnd));
        }

//        if (!Strings.isNullOrEmpty(bean.getPic())) bean.setPhotos(bean.getPic());
        if (Strings.isNullOrEmpty(bean.getPic()) && !Strings.isNullOrEmpty(bean.getPhotos())) {
            List<String> pics = Arrays.asList(bean.getPhotos().split(";"));
            bean.setPic(pics.get(0));
        } else if (!Strings.isNullOrEmpty(bean.getPic()) && bean.getPic().indexOf(";") > 0) {
            List<String> pics = Arrays.asList(bean.getPic().split(";"));
            bean.setPic(pics.get(0));
        }

        Integer i = 0;
        String rkey = Constants.REDIS_GOODS_LIST + ObjectUtil.getMid() + "_" + ObjectUtil.getMpid() + "_" + bean.getCid() + "_";
        for (i = 0; i < 10; i++) {
            redisService.del(rkey + i.toString());
        }

        MerchantConfig mconfig = redisService.getMconfig();
        if (bean.getJifen() == null) {
            bean.setJifen(mconfig.getIsJifen());
        }
        if (bean.getIsMember() == null) {
            bean.setIsMember(mconfig.getIsMember());
        }
        if (bean.getIsCoupon() == null) {
            bean.setIsCoupon(mconfig.getIsCoupon());
        }
        if (bean.getIsShare() == null) {
            bean.setIsShare(mconfig.getIsShare());
        }
        if (bean.getTimeout() == null) {
            bean.setTimeout(3);
        }

        BigDecimal zero = new BigDecimal(0);
        //===待完善：仅平台型活动支持促销成本一说
        //******* bean.getType().intValue() > 0 **********
        if (bean.getSaleprice() != null && bean.getMinPrice() == null && bean.getType() != null && bean.getType().intValue() > 0 && mconfig.getPromotionCost() != null) {
            //促销成本
            bean.setMinPrice(bean.getSaleprice().multiply(mconfig.getPromotionCost()));
        }

        //平台入驻商家
        //非平台入驻商家，商家自营的，无需处理营销成本
        if (bean.getSid() != null && bean.getSid().longValue() > 0) {
            if (bean.getSaleprice() != null && bean.getSaleprice().doubleValue() > 0) {
                //【商品活动级别默认处理分润】
                Mdpay mdpay = mdpayMapper.selectById(bean.getSid());

                if (mdpay == null) {
                    Mdpay entity = new Mdpay();
                    entity.setMpid(bean.getMpid());
                    entity.setSid(-bean.getMpid());
                    mdpay = mdpayMapper.selectById(entity);
                }
                Store store = redisService.getStore(bean.getSid());
                if (mdpay != null && store.getLeagueid() != null) {
                    //===待完善
                    //1、优先计算平台收款，保证平台成本
                    bean.setPtfan(bean.getSaleprice().multiply(mdpay.getPayplat()));
                    //1、其次计算商家收款，保证商家成本
                    bean.setLmfan(bean.getSaleprice().multiply(mdpay.getPaymeng()));

                    //3、最后计算分佣
                    if (bean.getShareBonusType() != null && bean.getShareBonusType() == XffanType.qian.getVal()
                            && bean.getShareMount() != null && bean.getShareMount().doubleValue() > 0) {

                    } else {
                        bean.setShareMount(new BigDecimal(0));
                    }
                    bean.setMinPrice(bean.getSaleprice().subtract(bean.getPtfan()).subtract(bean.getLmfan()).subtract(bean.getShareMount()));

                    //===待完善
                    //矫正，如果审批实物，联盟利润为零,分享利润太高
                    if (bean.getLmfan().doubleValue() < 0) {
                        info.setCode(1);
                        info.setMsg("佣金分配不合理请重新设置");
                        return info;
                    }
                } else {
                    //无联盟无代理模式分润
                    //活动商品成交价=商家收款+平台收佣+推荐人佣金
                    //该模式相对简单
                    //处理分佣
                    bean.setPtfan(bean.getSaleprice());
                    bean.setLmfan(new BigDecimal(0));

                    if (bean.getShareBonusType() != null && bean.getShareBonusType() == XffanType.qian.getVal()
                            && bean.getShareMount() != null && bean.getShareMount().doubleValue() > 0) {

                    } else {
                        bean.setShareMount(new BigDecimal(0));
                    }
                    //商家入账
                    bean.setMinPrice(bean.getSaleprice().subtract(bean.getPtfan()).subtract(bean.getLmfan()).subtract(bean.getShareMount()));
                }
            }
        } else {
            //非平台型，商家自营行
            //minprice==针对入驻商家的成本
            bean.setSid(null);
            if (bean.getSaleprice() != null && bean.getSaleprice().doubleValue() > 0) {
                if (bean.getShareBonusType() != null && bean.getShareBonusType() == XffanType.qian.getVal()
                        && bean.getShareMount() != null && bean.getShareMount().doubleValue() > 0) {
                    //校验
                    if (bean.getShareMount().doubleValue() > bean.getSaleprice().doubleValue()) {
                        info.setCode(1);
                        info.setMsg("佣金设置有误");
                        return info;
                    }

                    //非平台入驻商家，商家自营的，且有分享奖金+奖励模式是普通模式
                    if (bean.getFxmode() != null && bean.getFxmode() == Fxmode.common.getVal()) {
                        bean.setPtfan(bean.getSaleprice().subtract(bean.getShareMount()));
                    } else if (bean.getFxmode() != null && bean.getFxmode() == Fxmode.fexiao.getVal()) {
                        //非平台入驻商家，商家自营的，且有分享奖金+奖励模式是分销模式，在支付成功生成订单时处理
                    } else if (bean.getFxmode() != null && bean.getFxmode() == Fxmode.jieti.getVal()) {
                        //===待完善
                        //非平台入驻商家，商家自营的，且有分享奖金+奖励模式是阶梯模式
                    }
                } else {
                    //没有设置佣金
                    bean.setPtfan(bean.getSaleprice());//商家自营行
                }
            }
        }
        if (bean.getSid() != null) {
            Store store = redisService.getStore(bean.getSid());
            bean.setSname(store.getName());
        }

        if (mconfig.getIsMultishop() == -1) {
            bean.setStatus(2);
        }
        bean.insert();
        //更新素材资源
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Goods@" + bean.getId() + "@insert", ActorRef.noSender());

        logger.debug("-----------------------------------------after bean.insert() goods=" + JSON.toJSONString(bean));

        if (toupiao != null && toupiao.getDanripiao() != null) {
            toupiao.setGid(bean.getId());
            toupiao.setCreatetime(bean.getCreatetime());
            toupiao.insert();
        }

        if (bean.getMusicid() != null) {
            GoodsMusic goodsMusic = new GoodsMusic();
            goodsMusic.setGid(bean.getId());
            goodsMusic.setMusicid(bean.getMusicid());
            goodsMusic.setMpid(bean.getMpid());
            goodsMusic.setCreatetime(bean.getCreatetime());
            goodsMusic.insert();
        }

        if (bean.getSid() != null) {
            StoreStat storeStat = storeStatMapper.selectById(bean.getSid());
            if (storeStat == null) {
                storeStat = new StoreStat();
                storeStat.setStoreid(bean.getSid());
            }
            storeStat.setGoods(storeStat.getGoods() + 1);
            storeStat.setModifytime(new Date());
            storeStat.setMpid(ObjectUtil.getUid());
            storeStat.updateById();
        }

        if (bean.getSid() != null) {
            GoodsStore goodsStore = new GoodsStore();
            goodsStore.setGid(bean.getId());
            goodsStore.setSid(bean.getSid());
            goodsStore.setState(1);
            goodsStore.setMid(bean.getMid());
            goodsStore.setMpid(bean.getMpid());
            goodsStore.setUid(bean.getUid());
            goodsStore.setCreatetime(new Date());
            if (bean.getSid() != 3766)
                goodsStore.insert();
        }

        //处理抽奖活动
        //保存抽奖奖品关联
        int stores = 0;
        if (bean.getType() != null && bean.getType() == YXType.choujiang.getVal() && !Strings.isNullOrEmpty(jps)) {
            List<String> jpslistr = Arrays.asList(jps.split(","));
            for (String item : jpslistr) {
                Choujiang choujiang = new Choujiang();
                choujiang.setId(Long.parseLong(item));
                choujiang.setState(1);
                choujiang.setGid(bean.getId());
                choujiang.setModifier(bean.getUid());
                choujiang.setModifytime(new Date());
                choujiang.updateById();

                Choujiang ochoujiang = choujiangService.selectOne(new EntityWrapper<Choujiang>().setSqlSelect("num").eq("id", choujiang.getId()));
                stores += ochoujiang.getNum();
            }
            Goods ngoods = new Goods();
            ngoods.setId(bean.getId());
            ngoods.setStores(stores);
            ngoods.setPtotal(0);
            ngoods.updateById();
        }

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_GOODS_MODIFY + "@" + bean.getId(), ActorRef.noSender());

        logger.debug("---------------------------------start to save goods" + JSON.toJSONString(bean));
        Map<String, Object> map = new HashMap();
        map.put("gid", bean.getId());
        map.put("gname", bean.getName());
        info.setInfo(map);

        return info;
    }

    //新版带商家信息的商品列表
    //获取目录商品，通过cid查询，cid == -2:查询会员商品；cid==0时，查询全部商品
    @RequestMapping("/api/goods/mdlist")
    @ResponseBody
    public Jinfo mdlist(@RequestParam(value = "cid", required = false) Long cid,
                        @RequestParam(value = "sid", required = false) Long sid,
                        @RequestParam(value = "orderby", required = false) Integer orderby,
                        @RequestParam(value = "isadmin", required = false) Integer isadmin,
                        @RequestParam(value = "sort", required = false) Integer sort,
                        @RequestParam(value = "pname", required = false) String pname,
                        @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                        HttpServletRequest req) {
        Jinfo json = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();

        //默认分类的第一页商品（前10）目缓存到redis
        String rkey = Constants.REDIS_GOODS_LIST + mid + "_" + ObjectUtil.getMpid() + "_" + cid + "_" + pageIndex;
        MerchantConfig mc = redisService.getMconfig();
        logger.debug("========rkey=" + rkey);
        List<Goods> goods = redisService.get(rkey);
        //Strings.isNullOrEmpty(pname) 不是搜索
        boolean notsou = Strings.isNullOrEmpty(pname);
        if (notsou && goods != null && goods.size() > 0) {
            logger.debug("========rkey value=" + goods);
            json.setInfo(goods);
            return json;
        }

        Page page = new Page(pageIndex, pageSize);

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>();
        if (cid != null && cid == -2) wrapper.isNotNull("hyprice");
        else if (cid != null && cid != 0) wrapper.eq("cid", cid);
        else wrapper.gt("cid", 0);

        if (sid != null && sid > 0) {
            Store store = storeService.selectOne(new EntityWrapper<Store>()
                    .setSqlSelect("id,name").eq("mpid", ObjectUtil.getMpid()).eq("state", 1));
            if (store != null) sid = store.getId();
        }
        if (sid != null) wrapper.eq("sid", sid);

        //只支持一个字段搜索
//       if (!Strings.isNullOrEmpty(pname)) wrapper.like("name", pname).or().like("characteristic", pname);

        if (!notsou) wrapper.like("name", pname);
        wrapper.eq("mpid", mpid);
        if (isadmin == null) wrapper.eq("state", 1);

        String by = "cid";
        if (orderby != null) {
            switch (orderby) {
                case 1:
                    by = "number_sale";
                    break;
                case 2:
                    by = "createtime";
                    break;
                case 3:
                    by = "saleprice";
                    break;
                default:
                    by = "sort";
                    sort = -1;
            }
            wrapper.orderBy(by, sort == -1);
        } else {
            wrapper.orderBy("sort");
        }

        //华口云特殊过滤
        User user = redisService.getUser();
        if (ObjectUtil.getMpid() == 11 && user != null && user.getIsPlatform() != 1 && user.getIsMch() != 1
                && cid != null && (cid == 0 || cid == 828)) {
            wrapper.ne("cid", 808);
        } else if (ObjectUtil.getMpid() == 11 && user == null && cid != null && (cid == 0 || cid == 828)) {
            wrapper.ne("cid", 808);
        }

        Page<Goods> list = goodsService.selectPage(page, wrapper);
        List<Goods> glist = list.getRecords();
        if (glist != null && glist.size() > 0 && cid != null && cid > 0) {
            for (Goods g : glist) {
                g.setNumber(0);
            }
        }
        json.setInfo(list.getRecords());
        if (pageIndex <= 1 && mc.isCached() && !notsou) redisService.set(rkey, list.getRecords());
//       else if (pageIndex == 2 && pageIndex < 10 && mc.isCached())
//           redisService.set(rkey, list.getRecords(), 10, TimeUnit.MINUTES);
        return json;
    }

    private List<Goods> processSKuGoods(List<Goods> list) {
        logger.debug("-------------------------------------processSKuGoods");
        for (Goods goods : list) {

            Long gid = goods.getId();
            Long mpid = goods.getMpid();

            Wrapper<GoodsSku> entity = new EntityWrapper<GoodsSku>()
                    .setSqlSelect("id,gid,cid,characteristic,pic,price,xiangou,saleprice,saleprice,logistics_id logisticsId," +
                            "is_member isMember,is_jifen isJifen,is_coupon isCoupon,max_use_jifen maxUseJifen,gtype,extids,ext1,ext2,ext3,ext4,ext5,stores")
                    .eq("mpid", mpid)
                    .eq("gid", gid);

            List<GoodsSku> skulist = goodsSkuService.selectList(entity);
            logger.debug("-------------------------------------processSKuGoods 111");
            if (goods.getHasSku() != null && goods.getHasSku() == 1 && skulist != null && skulist.size() > 0) {
                //add redis cache
                String rkey = "goods_detail_skugg_" + gid;
                String rkeymulExtids = "goods_detail_mulExtids_" + gid;
                String rkeySkuinfo = "goods_detail_skuinfo_" + gid;
                logger.debug("-------------------------------------processSKuGoods 222");
                RBucket<String> bucket = redis.getBucket(rkey);
                RBucket<String> bucketmulExtids = redis.getBucket(rkeymulExtids);
                RBucket<String> bucketSkuinfo = redis.getBucket(rkeySkuinfo);
                if (bucket.isExists() && !Strings.isNullOrEmpty(bucket.get())) {
                    goods.setSkugg(bucket.get());
                    goods.setMulExtids(bucketmulExtids.get());
                    goods.setSkuinfo(bucketSkuinfo.get());
                } else {
                    List<String> skuids = new ArrayList<String>();
                    TreeSet<String> exts = new TreeSet<String>();
                    for (GoodsSku item : skulist) {
                        if (Strings.isNullOrEmpty(item.getExtids())) continue;

                        skuids.add(item.getId().toString());
                        String[] extsArr = item.getExtids().split("_");
                        for (String e : extsArr) {
                            exts.add(e);
                        }
                    }

                    logger.info("============exts=" + exts.toString());
                    Wrapper<Config> centity = new EntityWrapper<Config>()
                            .setSqlSelect("pid").in("id", exts);//父类规格
                    logger.info("============centity=" + JSON.toJSONString(centity));
                    List<Config> cslist = configService.selectList(centity);

                    logger.info("============cslist=" + JSON.toJSONString(cslist));
                    exts.clear();
                    for (Config item : cslist) {
                        exts.add(item.getPid().toString());
                    }
                    centity = new EntityWrapper<Config>()
                            .setSqlSelect("id,name").in("id", exts).orderBy("sort");
                    cslist = configService.selectList(centity);

                    for (Config item : cslist) {
                        item.setChilds(new TreeSet<Config>());
                    }
                    logger.info("======after======cslist=" + JSON.toJSONString(cslist));

                    List<GoodsSku> goodsku = skulist;
                    TreeMap<String, GoodsSku> skuMap = new TreeMap<String, GoodsSku>();
                    List<String> extidsList = new ArrayList<String>();
                    TreeMap<String, Boolean> mulExtidsList = new TreeMap<String, Boolean>();
                    for (GoodsSku item : goodsku) {
                        skuMap.put(item.getExtids(), item);
                        extidsList.add(item.getExtids());
                    }
                    for (String item : extidsList) {
                        String[] arr = item.split("_");
                        for (int i = 0; i < arr.length; i++) {
                            mulExtidsList.put(appendArr(arr, i), true);
                        }
                    }

                    goods.setMulExtids(JSON.toJSONString(mulExtidsList));
                    goods.setSkuinfo(JSON.toJSONString(skuMap));

                    bucketmulExtids.set(goods.getMulExtids());
                    bucketSkuinfo.set(goods.getSkuinfo());

                    JSONArray jscon = new JSONArray();
                    int m = 0;
                    for (int i = 0; i < cslist.size(); i++) {
                        Config inc = cslist.get(i);
                        inc.setDisabled(false);
                        for (GoodsSku item : goodsku) {
                            String[] extids = item.getExtids().split("_");
                            Config config = new Config();
                            config.setDisabled(false);
                            logger.info("======cslist.get()======" + i);
                            if (Strings.isNullOrEmpty(extids[i]) || extids[i].equals("null")) continue;
                            config.setId(Long.valueOf(extids[i]));
                            if (i == 0) {
                                //1级规格
                                config.setName(item.getExt1());
//                              extidStart = config.getId().toString();
                            }
                            if (i == 1) {
                                //2级规格
                                config.setName(item.getExt2());
//                              extidStart = selext.get(0)+"_"+config.getId().toString();
                            }
                            if (i == 2) {
                                //3级规格
                                config.setName(item.getExt3());
//                              extidStart = selext.get(0)+"_"+selext.get(1)+"_"+config.getId().toString();
                            }
                            if (i == 3) {
                                //4级规格
                                config.setName(item.getExt4());
//                              extidStart = selext.get(0)+"_"+selext.get(1)+"_"+selext.get(2)+"_"+config.getId().toString();
                            }
                            if (i == 4) {
                                config.setName(item.getExt5());
//                              extidStart = selext.get(0)+"_"+selext.get(1)+"_"+selext.get(2)+"_"+selext.get(3)+"_"+config.getId().toString();
                            }

                            config.setSort(m + 1);
                            m++;
                            inc.getChilds().add(config);
                            m = inc.getChilds().size();
                            logger.info("======cslist.get()===for=over==" + i);
                        }
//               jscon.put(ppsa[i],inc);
                        jscon.add(inc);
                        inc.setSort(i + 1);
                        m = 0;
                    }
                    goods.setSkugg(JSON.toJSONString(jscon, SerializerFeature.SortField));
                    bucket.set(goods.getSkugg());
                }
                logger.debug("-------------------------------------processSKuGoods goods=" + JSON.toJSONString(goods));
            }
        }

        return list;
    }


    /*
     行业订单，针对C端
     */
    @RequestMapping("/api/goods/yxlist3")
    @ResponseBody
    public Jinfo yxlist3(@RequestParam(value = "orderby", required = false) String orderby,
                        @RequestParam(value = "search", required = false) String search,
                        @RequestParam(value = "shicode", required = false) String shicode,
                        @RequestParam(value = "status", required = false) String status,
                        @RequestParam(value = "lat", required = false) Double lat,
                        @RequestParam(value = "lng", required = false) Double lng,
                        @RequestParam(value = "hytype", required = false) String hytype,
                        @RequestParam(value = "yxtype", required = false) String yxtype,
                        @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                        HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;

        Long mpid = ObjectUtil.getMpid();
        logger.info("==============================yxtype=" + yxtype);
        logger.info("==============================hytype=" + hytype);
        List<Goods> list = goodsService.getYxgoodsList3(pageIndex, pageSize, lat, lng, mpid, hytype, yxtype, shicode, status, orderby);

        if (list != null) {
            for (Goods item : list) {
                item.setYxtypeName(Constants.YX_TYPE_MAP.get(item.getType().toString()));
                item.setHytypeName(Constants.HY_TYPE_MAP.get(item.getHytype().toString()));
            }
        }
        info.setInfo(list);
        return info;
    }
}
